コード例 #1
0
ファイル: server.py プロジェクト: NykuvL/blockchainMail
def start():
    global chain
    global data
    global new_blocks
    chain.load()
    sync()
    if chain.get_length() < 1:
        from_k = utils.get_private_key().decode()
        to_k = utils.get_public_key(from_k).decode()
        c = {'title': 'abc', 'content': '123', 'to': to_k, 'from': from_k}
        mail = Mail(to_k, c, from_k)
        b = Block()
        b.add_mail(mail)
        chain.add_block(b)
        new_blocks.append(b)
        data = pickle.loads(chain.last_block().data)
        chain.save()
    data = pickle.loads(chain.last_block().data)
    response = {
        'message': "OK, is fine!",
        'block_hash': chain.last_block().hash.decode(),
        'length': chain.get_length(),
        'accounts': len(data.account_verify)
    }
    # mail_chain.save()
    return jsonify(response), 200
コード例 #2
0
 def __init__(self, username, password):
     self.__username = username
     self.__password = password
     self.__pri_key = utils.get_private_key()
     self.__pub_key = utils.get_public_key(self.__pri_key)
     v = utils.sm3_hash(username.encode() + self.__pub_key)[:4]
     self.address = base58.b58encode(v).decode() + '@' + username
     pri_k = utils.sm3_hash(self.__username + self.__password)[:64]
     pub_k = utils.get_public_key(pri_k)
     code = utils.sm2_encrypt(pub_k, (self.__pri_key.decode() + '@' +
                                      self.__username).encode())
     self.verification = code  # 验证口令
コード例 #3
0
    def clean(self, value):
        try:
            captcha_response = captcha.submit(
                value.get('recaptcha_challenge_field'),
                value.get('recaptcha_response_field'),
                get_private_key(),
                '', # remote user's IP address.  See footnotes.
            )
        except Exception: # this is probably bad.
            error_message = get_error_message('recaptcha-not-reachable')
            raise ValidationError(error_message)

        if not captcha_response.is_valid:
            error_message = get_error_message(captcha_response.error_code)
            raise ValidationError(error_message)

        return value
コード例 #4
0
ファイル: server.py プロジェクト: NykuvL/blockchainMail
def mine():
    global waiting_mail
    global new_blocks
    sync()
    if len(waiting_mail) < 1:
        from_k = utils.get_private_key().decode()
        to_k = utils.get_public_key(from_k).decode()
        c = {'title': '000', 'content': '000', 'to': to_k, 'from': from_k}
        m = Mail(to_k, c, from_k)
        mail = {'content': m, 'to': '000', 'from': '000'}
        waiting_mail.append(mail)

    print(len(waiting_mail))
    block = Block()
    b_loc = chain.last_block().index + 1
    for mail in waiting_mail:
        index = block.add_mail(mail['content'])
        to_addr = mail['to']
        from_addr = mail['from']
        location = [b_loc, index]
        if data.addr_rec_mail.get(to_addr) is None:
            data.addr_rec_mail[to_addr] = []
        data.addr_rec_mail[to_addr].append(location)
        print(to_addr, location)
        if data.addr_send_mail.get(from_addr) is None:
            data.addr_send_mail[from_addr] = []
        data.addr_send_mail[from_addr].append(location)
    waiting_mail.clear()
    block.data = pickle.dumps(data)
    chain.add_block(block)
    chain.save()
    new_blocks.append(block)
    response = {
        'message': 'new block is mined',
        'block_index': chain.last_block().index,
        'block_hash': chain.last_block().hash.decode(),
        'block_nonce': chain.last_block().nonce
    }
    for node in server_neighbours:
        requests.get('http://{}/'.format(node))
    return jsonify(response), 200
コード例 #5
0
def run_server(host, port, pk_file, pw_file, http_provider):
    private_key = get_private_key(pk_file, pw_file)
    import dbot
    dbot_server = dbot.get_server()
    dbot_server.init(app, private_key, http_provider)
    # save dbot backend info for dbot-service tool to operate dbot-service
    app_dir = os.path.join(os.path.expanduser('~'), '.dbot-server')
    if not os.path.exists(app_dir):
        os.makedirs(app_dir)
    with open(os.path.join(app_dir, '.backend'), 'w') as fh:
        json.dump(
            {
                'backend': 'http://{}:{}'.format(host, port),
                'pk_file': os.path.abspath(pk_file),
                'pw_file': os.path.abspath(pw_file),
                'http_provider': http_provider
            },
            fh,
            indent=2)
    app.run(host=host,
            port=port,
            debug=app.config['DEBUG'],
            use_reloader=False)
コード例 #6
0
ファイル: client.py プロジェクト: blocus/serverUpdater
#!/usr/bin/env python
# coding: utf-8

import getpass
import socket, string, random, subprocess, os
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA384
import utils

key = utils.get_private_key('update')

host, port = "127.0.0.1", 2356  #int(input('port :'))

mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

mySocket.connect((host, port))
while True:

    # Step 1 : Receive session_key
    while True:
        session_key = mySocket.recv(1024)
        if (session_key):
            print(session_key)
            break

    # Step 2 : encrypt session_key and send it
    signer = pkcs1_15.new(key)
    signature = SHA384.new()
    signature.update(session_key)
    mySocket.send(signer.sign(signature))
コード例 #7
0
ファイル: main.py プロジェクト: chrouzz/dbot-server
import os
import json
import logging
import logging.config

from app import create_app
from utils import get_private_key
from log import DBotLogger

app_name = 'dbot_server'
logging.config.dictConfig(DBotLogger(app_name).config())
app = create_app(app_name, os.environ.get('APP_ENV', 'Production'))

pk_file = './keystore/keyfile'
pw_file = './password/passwd'
private_key = get_private_key(pk_file, pw_file)

# import dbot module after logging config
import dbot
dbot_server = dbot.get_server()
logging.info('Start dbot server ...')
http_provider = os.environ.get('WEB3_PROVIDER', app.config['WEB3_PROVIDER_DEFAULT'])
dbot_server.init(app, private_key, http_provider)
logging.info('waiting for all dbot service sync info with block chain')

host = app.config['HOST']
port = os.environ.get('LISTEN_PORT', app.config['PORT'])

if __name__ == "__main__":
    app.run(host=host, port=port, debug=app.config['DEBUG'], use_reloader=False)
コード例 #8
0
 def __init__(self, pass_phrase, host, port, *args, **kwargs):
     super(User, self).__init__(*args, **kwargs)
     self._private_key = get_private_key(pass_phrase)
     self._public_key = get_public_key(pass_phrase)
     self._host = host
     self._port = port
コード例 #9
0
def create_and_send_tx(client_socket: socket.socket, user):
    sender = utils.get_public_key(user)
    command = gui_metadata(TX_COMMAND)
    client_socket.send(command)

    inputs = []
    N_inputs = int.from_bytes(client_socket.recv(4), 'little')
    for _ in range(N_inputs):
        input_data = client_socket.recv(159)
        inputs.append(utils.decode_input(input_data))

    input_choices = [
        {
            'name': f'txID: {input.where_created} value: {input.value}',
        }
        for index, input in enumerate(inputs)
    ]

    recipient_choices = [
        {
            'name': 'Alice',
        }, {
            'name': 'Bob',
        }, {
            'name': 'Charlie',
        }, {
            'name': 'No more pays',
        },
    ]

    actions = [{
        'type': 'checkbox',
        'name': INPUT_INDEX,
        'message': 'Selecciona los inputs a ingresar en la transacción',
        'choices': input_choices,
    }]

    recipient_actions = [{
        'type': 'list',
        'name': 'recipient',
        'message': 'Selecciona a la persona que le pagarás',
        'choices': recipient_choices,
    }]

    value_actions = [{
        'type': 'input',
        'name': 'value',
        'message': '¿Cuánto le vas a pagar?',
    }]

    answers = prompt(actions)
    inputs_selected = answers.get(INPUT_INDEX)
    inputs_to_pay = []
    for inputs_selected in inputs_selected:
        index = input_choices.index({'name': inputs_selected})
        inputs_to_pay.append(inputs[index])

    outputs = []
    while True:
        answers = prompt(recipient_actions)
        answer = answers['recipient']
        if answer == 'No more pays':
            break

        recipient = utils.get_public_key(answer)
        answers = prompt(value_actions)
        value = int(answers['value'])
        output = Output(value, recipient)
        outputs.append(output)

    unsigned = UnsignedTransaction(PAYCOINS_TYPE, inputs_to_pay, outputs)
    to_sign = unsigned.DataForSigs()
    signs = {}
    signs[sender.export_key(format='DER')] = sign(to_sign, utils.get_private_key(user))
    transaction = Transaction(unsigned, signs)
    client_socket.send(transaction.serialize())