Exemple #1
0
    def test_generate_key_pair_signature_and_verify(self):
        private_key_file_path = join_with_root(private_key_file)
        password_path = join_with_root(private_key_password_file)

        with open(password_path) as f:
            password = f.read()

        print(password)
        new_pri_key, pub_key = ECCipher.load_key_pair(private_key_file_path,
                                                      password)

        sample = b"qZaQ6S"
        print("gen prikey:", new_pri_key)

        self.assertIsNotNone(new_pri_key)

        new_signature = ECCipher.create_signature(new_pri_key, sample)
        print("new_signature is:", new_signature)
        self.assertIsNotNone(new_signature)

        # pub_key = ECCipher.create_public_key(new_pub_key)
        is_valid_sign = ECCipher.verify_sign(pub_key, new_signature, sample)

        print("is valid new_signature:", is_valid_sign)
        self.assertTrue(is_valid_sign)
Exemple #2
0
    def test_load_key_pair_from_private_key_and_verify_signature(self):

        private_key_file_path = join_with_root(private_key_file)
        password_path = join_with_root(private_key_password_file)

        with open(password_path) as f:
            password = f.read()

        print(password)
        pri_key, pub_key = ECCipher.load_key_pair(private_key_file_path,
                                                  password)

        # ---------- sign and verify ------------
        data = "testdata"
        new_signature = ECCipher.create_signature(pri_key, data)
        print("new_signature is:" + new_signature.hex())

        is_valid_sign = verify_geth_signature(pub_key, new_signature, data)
        print("is valid new_signature:" + str(is_valid_sign))
        self.assertTrue(is_valid_sign, "should be success")

        is_valid_sign = verify_geth_signature(pub_key, new_signature,
                                              data + "error")
        print("is valid new_signature:" + str(is_valid_sign))
        self.assertFalse(is_valid_sign, "should be failed")
Exemple #3
0
    def setUp(self):
        private_key_file_path = join_with_root(private_key_file)
        password_path = join_with_root(private_key_password_file)
        with open(password_path) as f:
            password = f.read()

        self.private_key_file_path = private_key_file_path
        self.password = password
Exemple #4
0
def main():
    if len(sys.argv) != 3:
        src_path = join_with_root(config.chain.contract_src_path)
        abi_path = join_with_root(config.chain.contract_bin_path)
    else:
        src_path = sys.argv[1]
        abi_path = sys.argv[2]

    compile_contract(src_path, abi_path)
Exemple #5
0
def main():
    bin_path = join_with_root(config.chain.contract_bin_path)
    contract_name = config.chain.contract_name
    contract = deploy_contract(bin_path, contract_name)

    registrar_path = join_with_root(config.chain.registrar_json)
    with open(registrar_path, 'w') as f:
        f.write(json.dumps(dict({contract_name: contract.address})))

    print("contract address: %s" % contract.address)
 def load_private_key():
     with open(join_with_root(config.wallet.rsa_private_key_password_file), "rb") as f:
         buyer_rsa_private_key_password = f.read()
     with open(join_with_root(config.wallet.rsa_private_key_file), "rb") as key_file:
         buyer_private_key = serialization.load_pem_private_key(
             key_file.read(),
             password=buyer_rsa_private_key_password,
             backend=default_backend()
         )
     return buyer_private_key
Exemple #7
0
def get_ssl_cert():
    server_key = join_with_rc(config.proxy.server_key)
    server_crt = join_with_rc(config.proxy.server_crt)

    if not os.path.isfile(server_key):
        logger.info("SSL key/cert file not found, " +
                    "run local self-test by default")
        server_key_sample = 'cpchain/assets/proxy/key/server.key'
        server_crt_sample = 'cpchain/assets/proxy/key/server.crt'
        server_key = join_with_root(server_key_sample)
        server_crt = join_with_root(server_crt_sample)

    return server_key, server_crt
Exemple #8
0
    def __init__(self, main_wnd):
        self.main_wnd = main_wnd

        self.url = config.market.market_url
        private_key_file_path = join_with_root(config.wallet.private_key_file)
        password_path = join_with_root(config.wallet.private_key_password_file)

        with open(password_path) as f:
            password = f.read()
        self.priv_key, self.pub_key = crypto.ECCipher.geth_load_key_pair_from_private_key(
            private_key_file_path, password)
        self.token = ''
        self.nonce = ''
        self.message_hash = ''
Exemple #9
0
    def setUp(self):
        private_key_file_path1 = join_with_root(private_key_file1)
        private_key_file_path2 = join_with_root(private_key_file2)
        password_path = join_with_root(private_key_password_file)

        with open(password_path) as f:
            password = f.read()

        self.pri_key, self.pub_key = ECCipher.load_key_pair(private_key_file_path1, password)
        self.pri_key_2, self.pub_key_2 = ECCipher.load_key_pair(private_key_file_path2, password)

        self.pub_key_string = ECCipher.serialize_public_key(self.pub_key)
        self.pub_key_string2 = ECCipher.serialize_public_key(self.pub_key_2)

        self.address = ECCipher.get_address_from_public_key(self.pub_key)
        self.address_2 = ECCipher.get_address_from_public_key(self.pub_key_2)
Exemple #10
0
 def proxy_claim_relay(self):
     proxy_trans = ProxyTrans(default_web3, config.chain.core_contract)
     private_key_file_path = join_with_root(config.wallet.private_key_file)
     password_path = join_with_root(config.wallet.private_key_password_file)
     with open(password_path) as f:
         password = f.read()
     priv_key, pub_key = ECCipher.geth_load_key_pair_from_private_key(
         private_key_file_path, password)
     priv_key_bytes = Encoder.str_to_base64_byte(priv_key)
     digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
     digest.update(
         ECCipher.generate_signature(priv_key_bytes,
                                     to_bytes(self.trade.order_id),
                                     password))
     deliver_hash = digest.finalize()
     tx_hash = proxy_trans.claim_relay(self.trade.order_id, deliver_hash)
     return tx_hash
Exemple #11
0
    def start_service(self,
                      ip=None,
                      ctrl_port=None,
                      data_port=None,
                      account_id=0):

        self.ip = ip
        set_proxy_account(account_id)
        self.peer_id = get_proxy_id()

        server_key = os.path.expanduser(join_with_rc(config.proxy.server_key))
        server_crt = os.path.expanduser(join_with_rc(config.proxy.server_crt))

        if not os.path.isfile(server_key):
            logger.info("SSL key/cert file not found, " +
                        "run local self-test by default")
            server_key_sample = 'cpchain/assets/proxy/key/server.key'
            server_crt_sample = 'cpchain/assets/proxy/key/server.crt'
            server_key = join_with_root(server_key_sample)
            server_crt = join_with_root(server_crt_sample)

        # data channel
        data_port = (data_port or config.proxy.server_data_port)
        file_factory = Site(FileServer())
        reactor.listenSSL(
            data_port, file_factory,
            ssl.DefaultOpenSSLContextFactory(server_key, server_crt))

        # ctrl channel
        ctrl_port = (ctrl_port or config.proxy.server_ctrl_port)
        ctrl_factory = SSLServerFactory(data_port=data_port)
        reactor.listenSSL(
            ctrl_port, ctrl_factory,
            ssl.DefaultOpenSSLContextFactory(server_key, server_crt))

        self.service_port = ctrl_port

        def set_proxy_ip():
            if self.ip is None:
                # waiting for node bootstrap finish
                return reactor.callLater(1, set_proxy_ip)

            ctrl_factory.set_external_ip(self.ip)

        set_proxy_ip()
Exemple #12
0
    def download_data(self, src, dst):
        stream_channel = json.loads(src)
        ws_url = stream_channel['ws_url']
        dest_stream_id = dst

        cmd_path = join_with_root(
            'cpchain/storage_plugin/bin/replicate-stream')
        args = ['nohup', cmd_path, ws_url, dest_stream_id]
        log = open('/tmp/' + dest_stream_id, 'w')
        subprocess.Popen(args, stdout=log, stderr=log)
    def generate_private_key(password=b'cpchainisawesome') -> "returns key bytes":
        # Generate our key
        key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=4096,
            backend=default_backend()
        )

        # Write our key to disk for safe keeping
        with open(join_with_root(config.wallet.rsa_private_key_file), "wb") as f:
            f.write(key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=serialization.BestAvailableEncryption(password),
            ))

        with open(join_with_root(config.wallet.rsa_private_key_password_file), "wb") as f:
            f.write(password)
        return key
Exemple #14
0
def test_server_chain():
    os.chdir(root_dir)
    server_web3 = chain.default_web3
    # chain.utils.deploy_contract(config.chain.core_contract)
    buyertrans = BuyerAgent(server_web3, config.chain.core_contract)
    print(server_web3.eth.defaultAccount)
    # desc_hash_base64 = 'AQkKqDxtNIRJ+1V82J5lP2/fRj/zbJ+2n0GzUF52Wsc='
    # desc_hash = Encoder.str_to_base64_byte(desc_hash_base64)
    # public_key = RSACipher.load_public_key()
    # print('pubkey ' + str(len(public_key)))
    # order_info = OrderInfo(
    #     desc_hash=desc_hash,
    #     buyer_rsa_pubkey=public_key,
    #     seller=buyertrans.web3.eth.defaultAccount,
    #     proxy=buyertrans.web3.eth.defaultAccount,
    #     secondary_proxy=buyertrans.web3.eth.defaultAccount,
    #     proxy_value=10,
    #     value=20,
    #     time_allowed=100
    # )
    # test_server_id = buyertrans.place_order(order_info)
    # print(test_server_id)
    # buyertrans.withdraw_order(test_server_id)
    # print(buyertrans.query_order(test_server_id))
    order_num = buyertrans.get_order_num()
    print(order_num)
    latest_order_info = buyertrans.query_order(order_num - 1)
    private_key_file_path = join_with_root(config.wallet.private_key_file)
    password_path = join_with_root(config.wallet.private_key_password_file)
    with open(password_path) as f:
        password = f.read()
    priv_key, pub_key = ECCipher.load_key_pair_from_private_key(
        private_key_file_path, password)
    pub_key_bytes = Encoder.str_to_base64_byte(pub_key)
    pub_key_loaded = load_der_public_key(pub_key_bytes,
                                         backend=default_backend())
    # print(Encoder.str_to_base64_byte(pub_key))
    # print(len(Encoder.str_to_base64_byte(pub_key)))
    # print(pub_key_bytes_to_addr(Encoder.str_to_base64_byte(pub_key)))
    # print(len(pub_key_bytes_to_addr(Encoder.str_to_base64_byte(pub_key))))
    print(get_addr_from_public_key(pub_key_loaded))
    print(to_bytes(hexstr=latest_order_info[2]))
    print(len(to_bytes(hexstr=latest_order_info[2])))
Exemple #15
0
    def generate_private_key(
            password=b'cpchainisawesome') -> "returns key bytes":
        """
        generate private key with RSA.

        we can use it like this :

        priv_key =  RSACipher.generate_private_key(password=b'cpchainisawesome')

        pub_key = priv_key.public_key()

        pub_bytes = pub_key.public_bytes(encoding=serialization.Encoding.DER,
                                         format=serialization.PublicFormat.SubjectPublicKeyInfo)

        print(len(pub_bytes))

        Args:
            password:password bytes

        Returns:
            private key object

        """

        key = rsa.generate_private_key(public_exponent=65537,
                                       key_size=4096,
                                       backend=default_backend())

        # Write our key to disk for safe keeping
        with open(join_with_root(config.wallet.rsa_private_key_file),
                  "wb") as f:
            f.write(
                key.private_bytes(
                    encoding=serialization.Encoding.PEM,
                    format=serialization.PrivateFormat.TraditionalOpenSSL,
                    encryption_algorithm=serialization.BestAvailableEncryption(
                        password),
                ))

        with open(join_with_root(config.wallet.rsa_private_key_password_file),
                  "wb") as f:
            f.write(password)
        return key
Exemple #16
0
    def load_private_key():
        """
        load private key with key file and password file in cpchain.toml,
        key file path item: config.wallet.rsa_private_key_password_file
        password file path item: config.wallet.rsa_private_key_password_file

        Returns:
            private key object
        """
        with open(join_with_root(config.wallet.rsa_private_key_password_file),
                  "rb") as f:
            buyer_rsa_private_key_password = f.read()
        with open(join_with_root(config.wallet.rsa_private_key_file),
                  "rb") as key_file:
            buyer_private_key = serialization.load_pem_private_key(
                key_file.read(),
                password=buyer_rsa_private_key_password,
                backend=default_backend())
        return buyer_private_key
Exemple #17
0
 def __init__(self, wallet):
     self.wallet = wallet
     bin_path = join_with_root(config.chain.contract_bin_path)
     # deploy_contract(bin_path, config.chain.contract_name, default_w3)
     account = get_address_from_public_key_object(self.wallet.market_client.public_key)
     if default_w3:
         account = default_w3.toChecksumAddress(account)
         self.buyer = BuyerAgent(default_w3, bin_path, config.chain.contract_name, account)
         self.seller = SellerAgent(default_w3, bin_path, config.chain.contract_name, account)
         self.handler = Handler(self)
         self.monitor = Monitor(self)
 def _set_web3(self):
     if self.web3 is None:
         mode = config.chain.mode
         if mode == "test":
             provider = TestRPCProvider()
         elif mode == "falcon":
             provider = HTTPProvider(config.chain.falcon_provider_addr)
         else:
             provider = IPCProvider(
                 join_with_root(config.chain.ipc_provider_addr))
         self.web3 = Web3(provider)
         self.web3.eth.defaultAccount = self.web3.eth.accounts[0]
Exemple #19
0
    def _populate_accounts(self):
        key_dir = join_with_root(config.account.keystore_dir)
        ptn = osp.join(key_dir, 'UTC-*')

        # TODO for now, we use the password stored in the file
        key_passphrase = open(osp.join(key_dir, 'password')).read()
        for key_path in glob.glob(ptn):
            account = Account(key_path, key_passphrase)
            self.append(account)

        if len(self):
            self.default_account = self[0]
Exemple #20
0
    def publish_product(self, title, ptype=None):

        if not ptype:
            type_list = ['file', 'stream']
            ptype = type_list[randint(0, 1)]
        description = 'stress testing description'
        price = randint(1, 10000) * 0.01  # could not be zero now.
        tags = 'stress testing tags'
        now = datetime.now()
        start_date = now.isoformat()
        end_date = (now + timedelta(days=7)).isoformat()
        category = 'stress testing category'
        cover_image = join_with_root('cpchain/assets/wallet/icons/[email protected]')

        self.selected_id += 1

        return super().publish_product(self.selected_id, title, ptype,
                                       description, str(price), tags,
                                       start_date, end_date, category,
                                       cover_image)
def read_contract_address(contract_name):
    with open(join_with_root(config.chain.registrar_json)) as f:
        contracts = json.load(f)
    return contracts[contract_name]
def read_contract_interface(contract_name):

    with open(join_with_root(config.chain.contract_json)) as f:
        all_contracts = json.load(f)
        contract_interface = all_contracts['<stdin>:' + contract_name]
    return contract_interface
Exemple #23
0
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa

from cpchain.utils import join_with_root
from cpchain import config

# Generate our key
key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=4096,
    backend=default_backend()
    )

# Write our key to disk for safe keeping
with open(join_with_root(config.wallet.rsa_private_key_file), "wb") as f:
    f.write(key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.BestAvailableEncryption(b"cpchainisawesome"),
        ))

with open(join_with_root(config.wallet.rsa_private_key_password_file), "wb") as f:
    f.write(b"cpchainisawesome")
Exemple #24
0
class Player:
    contract_path = join_with_root(config.chain.contract_bin_path)
    contract_name = config.chain.contract_name

    def __init__(self, account):
        self.address = account.address
        self.account = account

        self.buyer_agent = BuyerAgent(w3, self.contract_path,
                                      self.contract_name, self.address)
        self.seller_agent = SellerAgent(w3, self.contract_path,
                                        self.contract_name, self.address)
        self.proxy_agent = ProxyAgent(w3, self.contract_path,
                                      self.contract_name, self.address)

        self.rsa_public_key = generate_rsa_public_key()

    def query_order(self, order_id):
        return self.seller_agent.query_order(order_id)

    def mockup_product(self):
        private_key = ECCipher.create_private_key(self.account.privateKey)
        public_key = ECCipher.create_public_key_from_private_key(private_key)
        public_key = ECCipher.serialize_public_key(public_key)

        price = randint(1, 10000) * 0.01
        return {
            'description': 'stress testing description',
            'signature':
            '304502201b31544ff65ebbfff3743a0b2536388e1f6cf2533de4bbf0ffab57d762f54d50022100a8101face8c6a6d2f0e01a9a01ea49d80598c880872db9e3c1e9eb27a23a2554',
            'cover_image': 'upload_images/20181127072441_13.png',
            'end_date': '2018-12-04T15:24:41.664517Z',
            'msg_hash': 'dRFWYcWC9TKujDo7mLiUCq00MthHezzkyncAGIdaEos=',
            'id': 53,
            'start_date': '2018-11-27T15:24:41.664517Z',
            'ptype': 'file',
            'seq': 0,
            'owner_address': public_key,
            'tags': 'stress testing tags',
            'price': price,
            'title': 'stress testing product',
            'category': 'stress testing category',
            'status': 0,
            'created': '2018-11-27T07:24:41.715315Z'
        }

    def buyer_place_order(self, product, proxy):
        buyer_rsa_pubkey = self.rsa_public_key

        desc_hash = Encoder.str_to_base64_byte(product['msg_hash'])

        public_key = ECCipher.create_public_key(
            Encoder.hex_to_bytes(product['owner_address']))
        seller_addr = w3.toChecksumAddress(
            ECCipher.get_address_from_public_key(public_key))
        proxy = w3.toChecksumAddress(proxy)

        product = OrderInfo(desc_hash=desc_hash,
                            buyer_rsa_pubkey=buyer_rsa_pubkey,
                            seller=seller_addr,
                            proxy=proxy,
                            secondary_proxy=proxy,
                            proxy_value=100,
                            value=product['price'],
                            time_allowed=3600 * 24)

        w3.personal.unlockAccount(self.account.address, _passphrase)

        order_id = self.buyer_agent.place_order(product)
        # w3.personal.lockAccount(self.account.address)

        # return -1 if failure
        return order_id

    def seller_confirm_order(self, order_id):
        w3.personal.unlockAccount(self.account.address, _passphrase)
        status = self.seller_agent.confirm_order(order_id)
        # w3.personal.lockAccount(self.account.address)

        return status

    def proxy_claim_fetched(self, order_id):
        w3.personal.unlockAccount(self.account.address, _passphrase)
        status = self.proxy_agent.claim_fetched(order_id)
        # w3.personal.lockAccount(self.account.address)

        return status

    def proxy_claim_delivered(self, order_id):
        w3.personal.unlockAccount(self.account.address, _passphrase)
        status = self.proxy_agent.claim_delivered(order_id, b'dummy')
        # w3.personal.lockAccount(self.account.address)

        return status

    def buyer_confirm_order(self, order_id):
        w3.personal.unlockAccount(self.account.address, _passphrase)
        status = self.buyer_agent.confirm_order(order_id)
        # w3.personal.lockAccount(self.account.address)

        return status
Exemple #25
0
from eth_keys import keys
from eth_keyfile import extract_key_from_keyfile

from cpchain import config

from cpchain.utils import join_with_root

priv_bytes = extract_key_from_keyfile(
    join_with_root(config.wallet.private_key_file),
    open(join_with_root(config.wallet.private_key_password_file)).read())

print(priv_bytes)
priv_key = keys.PrivateKey(priv_bytes)

pub_key = priv_key.public_key
addr = pub_key.to_address()
print(addr)