def ringsig_sign_substitute(msghash, priv, pub_xs, pub_ys): # Number of pubkeys n = len(pub_xs) # Create list of pubkeys as (x, y) points pubs = [(pub_xs[i], recover_y(pub_xs[i], bit(pub_ys, i))) for i in range(n)] # My pubkey my_pub = b.decode_pubkey(b.privtopub(priv)) # Compute my index in the pubkey list my_index = 0 while my_index < n: if pubs[my_index] == my_pub: break my_index += 1 assert my_index < n # Compute the signer's I value I = b.multiply(hash_to_pubkey(list(my_pub)), priv) # Select a random ephemeral key k = b.hash_to_int(b.random_key()) # Store the list of intermediate values in the "ring" e = [None] * n # Compute the entry in the ring corresponding to the signer's index kpub = b.privtopub(k) kmulpub = b.multiply(hash_to_pubkey(list(my_pub)), k) orig_left = hash_array([msghash, kpub[0], kpub[1], kmulpub[0], kmulpub[1]]) orig_right = hash_value(orig_left) e[my_index] = {"left": orig_left, "right": orig_right} # Map of intermediate s values (part of the signature) s = [None] * n for i in list(range(my_index + 1, n)) + list(range(my_index + 1)): prev_i = (i - 1) % n # In your position in the ring, set the s value based on your private # knowledge of k; this lets you "invert" the hash function in order to # ensure a consistent ring. At all other positions, select a random s if i == my_index: s[prev_i] = b.add_privkeys(k, b.mul_privkeys(e[prev_i]["right"], priv)) else: s[prev_i] = b.hash_to_int(b.random_key()) # Create the next values in the ring based on the chosen s value pub1 = b.subtract_pubkeys(b.privtopub(s[prev_i]), b.multiply(pubs[i], e[prev_i]["right"])) pub2 = b.subtract_pubkeys(b.multiply(hash_to_pubkey(list(pubs[i])), s[prev_i]), b.multiply(I, e[prev_i]["right"])) left = hash_array([msghash, pub1[0], pub1[1], pub2[0], pub2[1]]) right = hash_value(left) e[i] = {"left": left, "right": right} # Check that the ring is consistent assert (left, right) == (orig_left, orig_right) # Return the first value in the ring, the s values, and the signer's # I value in compressed form return (e[0]["left"], s, I[0], I[1] % 2)
def create_key(crypto): private_key = bitcoin.random_key() public_key = bitcoin.privtopub(private_key) c.execute('INSERT INTO crypto_key (crypto,public_key,private_key,encrypted_private_key,timestamp) VALUES(?,?,?,?,?)', (crypto,public_key,private_key,0,datetime.datetime.now())) conn.commit() return public_key
def Generate_random_private_key(): valid_private_key = False while not valid_private_key: private_key = bitcoin.random_key() decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.N return private_key
def do_populate(args): private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey( bitcoin.privkey_to_pubkey(private_key), "hex") words = generate_word_list(args.pool_size) batches = [] total_txn_count = 0 txns = [] for i in range(0, len(words)): txn = create_intkey_transaction( verb='set', name=words[i], value=random.randint(9000, 100000), private_key=private_key, public_key=public_key) total_txn_count += 1 txns.append(txn) batch = create_batch( transactions=txns, private_key=private_key, public_key=public_key) batches.append(batch) batch_list = batch_pb2.BatchList(batches=batches) print("Writing to {}...".format(args.output)) with open(args.output, "wb") as fd: fd.write(batch_list.SerializeToString())
def test_set_status(self): """Tests that set_status() has the correct behavior. Basically: 1. Adds a batch which has two transactions. 2. Calls next_transaction() to get the first Transaction. 3. Calls next_transaction() to verify that it returns None. 4. Calls set_status() to mark the first transaction applied. 5. Calls next_transaction() to get the second Transaction. Step 3 returns None because the first transaction hasn't been marked as applied, and the SerialScheduler will only return one not-applied Transaction at a time. Step 5 is expected to return the second Transaction, not None, since the first Transaction was marked as applied in the previous step. """ private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey( bitcoin.privkey_to_pubkey(private_key), "hex") context_manager = ContextManager(dict_database.DictDatabase()) squash_handler = context_manager.get_squash_handler() first_state_root = context_manager.get_first_root() scheduler = SerialScheduler(squash_handler, first_state_root) txns = [] for name in ['a', 'b']: txn = create_transaction( name=name, private_key=private_key, public_key=public_key) txns.append(txn) batch = create_batch( transactions=txns, private_key=private_key, public_key=public_key) scheduler.add_batch(batch) scheduled_txn_info = scheduler.next_transaction() self.assertIsNotNone(scheduled_txn_info) self.assertEquals('a', scheduled_txn_info.txn.payload.decode()) self.assertIsNone(scheduler.next_transaction()) scheduler.set_transaction_execution_result( scheduled_txn_info.txn.header_signature, is_valid=False, context_id=None) scheduled_txn_info = scheduler.next_transaction() self.assertIsNotNone(scheduled_txn_info) self.assertEquals('b', scheduled_txn_info.txn.payload.decode())
def create_encrypted_key(crypto,password): private_key = bitcoin.random_key() public_key = bitcoin.privtopub(private_key) # encrypt private key here encrypted_private_key=simplecrypt.encrypt(password=password,data=private_key) c.execute('INSERT INTO crypto_key (crypto,public_key,private_key,encrypted_private_key,timestamp) VALUES(?,?,?,?,?)', (crypto,public_key,0,encrypted_private_key,datetime.datetime.now())) conn.commit() return public_key
def test_transaction_order(self): """Tests the that transactions are returned in order added. Adds three batches with varying number of transactions, then tests that they are returned in the appropriate order when using an iterator. This test also creates a second iterator and verifies that both iterators return the same transactions. This test also finalizes the scheduler and verifies that StopIteration is thrown by the iterator. """ private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey( bitcoin.privkey_to_pubkey(private_key), "hex") context_manager = ContextManager(dict_database.DictDatabase()) squash_handler = context_manager.get_squash_handler() first_state_root = context_manager.get_first_root() scheduler = SerialScheduler(squash_handler, first_state_root) txns = [] for names in [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']]: batch_txns = [] for name in names: txn = create_transaction( name=name, private_key=private_key, public_key=public_key) batch_txns.append(txn) txns.append(txn) batch = create_batch( transactions=batch_txns, private_key=private_key, public_key=public_key) scheduler.add_batch(batch) scheduler.finalize() iterable1 = iter(scheduler) iterable2 = iter(scheduler) for txn in txns: scheduled_txn_info = next(iterable1) self.assertEqual(scheduled_txn_info, next(iterable2)) self.assertIsNotNone(scheduled_txn_info) self.assertEquals(txn.payload, scheduled_txn_info.txn.payload) scheduler.set_transaction_execution_result( txn.header_signature, False, None) with self.assertRaises(StopIteration): next(iterable1)
def do_generate(args): private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey( bitcoin.privkey_to_pubkey(private_key), "hex") words = generate_word_list(args.pool_size) batches = [] start = time.time() total_txn_count = 0 for i in range(0, args.count): txns = [] for _ in range(0, random.randint(1, args.batch_max_size)): txn = create_intkey_transaction( verb=random.choice(['inc', 'dec']), name=random.choice(words), value=1, private_key=private_key, public_key=public_key) total_txn_count += 1 txns.append(txn) batch = create_batch( transactions=txns, private_key=private_key, public_key=public_key) batches.append(batch) if i % 100 == 0 and i != 0: stop = time.time() txn_count = 0 for batch in batches[-100:]: txn_count += len(batch.transactions) fmt = 'batches {}, batch/sec: {:.2f}, txns: {}, txns/sec: {:.2f}' print(fmt.format( str(i), 100 / (stop - start), str(total_txn_count), txn_count / (stop - start))) start = stop batch_list = batch_pb2.BatchList(batches=batches) print("Writing to {}...".format(args.output)) with open(args.output, "wb") as fd: fd.write(batch_list.SerializeToString())
def init_code(self): import bitcoin for schema in self: x=schema.registry_pb pbmsg=base64.b64decode( x ) pbr = Registry() pbr.ParseFromString( pbmsg ) for m in pbr.models: self.env.cr.execute("select id from %s where code is Null"%m._table) for rec in self.env.cr.fetchall(): id_=rec[0] secret_key = bitcoin.random_key() pub_key = bitcoin.privtopub(secret_key) code = bitcoin.pubtoaddr( pub_key ) sql_update="update %s set " % m._table self.env.cr.execute( sql_update+"code=%s,secret_key=%s where id=%s", (code,secret_key,id_) )
def do_generate(args, batches, words): private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey( bitcoin.privkey_to_pubkey(private_key), "hex") start = time.time() total_txn_count = 0 for i in range(0, args.count): txns = [] for _ in range(0, random.randint(1, args.batch_max_size)): txn = create_intkey_transaction( verb=random.choice(['inc', 'dec']), name=random.choice(words), value=1, private_key=private_key, public_key=public_key) total_txn_count += 1 txns.append(txn) batch = create_batch( transactions=txns, private_key=private_key, public_key=public_key) batches.append(batch) if i % 100 == 0 and i != 0: stop = time.time() txn_count = 0 for batch in batches[-100:]: txn_count += len(batch.transactions) fmt = 'batches {}, batch/sec: {:.2f}, txns: {}, txns/sec: {:.2f}' print(fmt.format( str(i), 100 / (stop - start), str(total_txn_count), txn_count / (stop - start))) start = stop
def do_populate(args, batches, words): private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey( bitcoin.privkey_to_pubkey(private_key), "hex") total_txn_count = 0 txns = [] for i in range(0, len(words)): txn = create_intkey_transaction( verb='set', name=words[i], value=random.randint(9000, 100000), private_key=private_key, public_key=public_key) total_txn_count += 1 txns.append(txn) batch = create_batch( transactions=txns, private_key=private_key, public_key=public_key) batches.append(batch)
def op_init(opt, stack): DEPLOYMENT_NAME=opt.deployment_name dbname=stack.pop() conn,tp=get_connection(opt, dbname) assert tp=='pg' cr=conn.cursor() pb_fn = os.path.join(opt.pbdir, DEPLOYMENT_NAME + '.pb' ) pbr = Registry() pbr.ParseFromString( file(pb_fn).read() ) import bitcoin for m in pbr.models: cr.execute("select id from %s where code is Null"%m._table) for rec in cr.fetchall(): id_=rec[0] secret_key = bitcoin.random_key() pub_key = bitcoin.privtopub(secret_key) code = bitcoin.pubtoaddr( pub_key ) sql_update="update %s set " % m._table cr.execute( sql_update+"code=%s,secret_key=%s where id=%s", (code,secret_key,id_) ) cr.close() conn.commit()
def main(): ''' Our main function. ''' if os.path.isfile(SECRET_FILE): print('It seems you have already created the keys.') return 1 priv = bitcoin.encode_privkey(bitcoin.random_key(), 'wif') with open(SECRET_FILE, 'w') as secret_file: secret_file.write(priv) pub = bitcoin.privtopub(priv) with open(PUBLIC_FILE, 'w') as public_file: public_file.write(pub) address = bitcoin.pubtoaddr(pub, 0) with open(ADDRESS_FILE, 'w') as addres_file: addres_file.write(address) print('Generated {} and {}'.format(SECRET_FILE, PUBLIC_FILE)) print('Keep {} safe and back it up. Hint: Use scrypt to encrypt the key.'.format(SECRET_FILE)) print('Send BTC to {}'.format(address)) return 0
import bitcoin as bt #1st Sig private_key1 = bt.random_key() public_key1 = bt.privttopub(private_key1) #2nd Sig private_key2 = bt.random_key() public_key2 = bt.privttopub(private_key2) #3rd Sig private_key3 = bt.random_key() public_key3 = bt.privttopub(private_key3) multi_sig = bt.mk_multisig_script(public_key1, public_key2, public_key3, 2,3) btc_address = scriptaddr(multi_sig) #with open('data.txt', 'w') as fob: # fob.write('Private Key1: ' + private_key1 + '\nPrivate Key2: ' + private_key2 + '\nPrivate Key3: ' + private_key3 + 'nPublic Key1: ' + public_key1 + '\nPublic Key2: ' + public_key2 + '\nPublic Key3: ' + public_key3 + '\nBTC Address: '+bitcoin_address+'\n') # fob.close() print('Private Key1:', private_key1) print('Private Key2:', private_key2) print('Private Key3:', private_key3) print('BTC Address:', btc_address)
def createPrivateKey(self): self.private_key = bitcoin.random_key()
import bitcoin as bt #private Key private_key = bt.random_key() #public Key public_key = bt.privtopub(private_key) #bitcoin Address btc_address = bt.pubtoaddr(public_key) #also generates a text file if you like to save that #with open('data.txt', 'w') as fob: # fob.write('Private Key: '+private_key+'\nPublic Key: '+public_key+'\nBTC Address: '+btc_address+'\n') # fob.close() print('Private Key:', private_key) print('Public Key:', public_key) print('Bitcoin Address:', btc_address)
import bitcoin valid_private_key = False while not valid_private_key: private_key = bitcoin.random_key() decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.N print("Private key in hexadecimal is {}".format(private_key)) print("Private key in decimal is {}".format(decoded_private_key)) wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif') print("Private key in WIF is {}".format(wif_encoded_private_key)) compressed_private_key = private_key + '01' print("Private key compressed in hexadecimal {}".format(compressed_private_key)) wif_compressed_private_key = bitcoin.encode_privkey(bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif') print("Private key WIF compressed is {}".format(wif_compressed_private_key)) public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) print("Public key (x,y) coordinates is".format(public_key)) hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex') print("Hex encoded public key is {}".format(hex_encoded_public_key)) (public_key_x, public_key_y) = public_key if (public_key_y % 2) == 0: compressed_prefix = '02' else: compressed_prefix = '03' hex_compressed_public_key = compressed_prefix + bitcoin.encode(public_key_x, 16) print("Compressed Public Key (hex) is {}".format(hex_compressed_public_key)) print("Bitcoin Address (b58check) is {}".format(bitcoin.pubkey_to_address(public_key))) print("Compressed Bitcoin Address (b58check) is: {}".format(bitcoin.pubkey_to_address(hex_compressed_public_key)))
import bitcoin valid_private_key = False while not valid_private_key: private_key = bitcoin.random_key() decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.N print "Private key (hex) is:", bitcoin.random_key() print "Private key (decimal) is:", bitcoin.decode_privkey(private_key, 'hex') print "Largest possible Key size is", bitcoin.N print "2^256-1 is", 2**256-1
btc_transactions: typing.List[str]) -> typing.Iterator[str]: btc_addresses = set(btc_addresses) for btc_transaction in btc_transactions: cur_tx = client.getrawtransaction(btc_transaction, 1) for out in cur_tx['vout']: if out['scriptPubKey']['addresses'][0] in btc_addresses: yield { 'output': '{}:{}'.format(btc_transaction, out['n']), 'value': int(out['value'] * 10**8) } if __name__ == '__main__': bitcoin_client = BitcoinClient() _ensure_funds(bitcoin_client) keys = [bitcoin.random_key() + '01' for _ in range(3)] pubkeys = [bitcoin.privtopub(k) for k in keys] addresses = [bitcoin.pubtoaddr(p, magicbyte=111) for p in pubkeys] an_external_address = 'mwDWoUg8vdkpDWtFY6GZJybBqNEM6mmYaz' bitprint('\nPublic keys\n', pubkeys) bitprint('\nAddresses\n', addresses) # Total: 0.06 funding_txs = [ bitcoin_client.sendtoaddress(address, 0.01 * (i + 1)) for i, address in enumerate(addresses) ] bitprint('\nFunding txs') bitprint(funding_txs) outpoints = list(_get_outpoints(bitcoin_client, addresses, funding_txs))
def _private(): return bitcoin.random_key()
def secret_random_key(a): return bitcoin.random_key()
def new_priv_key(): return bitcoin.random_key()
def _make_key_pair(): private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey(bitcoin.privkey_to_pubkey(private_key), "hex") return private_key, public_key
N = bitcoin.N G = bitcoin.G fast_add = bitcoin.fast_add fast_multiply = bitcoin.fast_multiply def fast_substract(a, b): x1, y1 = a x2, y2 = b return fast_add((x1, y1), (x2, -y2)) inv = bitcoin.inv # We don't know d but we can get Q from emitted signatures d = bitcoin.decode_privkey(bitcoin.random_key()) Q = fast_multiply(G, d) # We build up a message to sign msghash = hashlib.sha256('a_random_message').hexdigest() z = bitcoin.hash_to_int(msghash) cpt = 0 while True: cpt = cpt + 1 r = random.SystemRandom().randrange(1, N) s = random.SystemRandom().randrange(1, N / 2) if r == fast_add(fast_multiply(G, z * inv(s, N)), fast_multiply(Q, r * inv(s, N)))[0]: break
def get_z(msg): hash = hashlib.sha256(msg).hexdigest() return bitcoin.hash_to_int(hash) def sign(z, k, priv): r, y = fast_multiply(G, k) s = (inv(k, N) * (z + r * bitcoin.decode_privkey(priv))) % N v, r, s = 27 + ((y % 2) ^ (0 if s * 2 < N else 1)), r, s if s * 2 < N else N - s return v, r, s # Generate secret key & the corresponding public key and address sk = bitcoin.random_key() pk = bitcoin.privtopub(sk) print('+ Priv key = {:s}'.format(sk)) # Sign 2 messages d = bitcoin.decode_privkey(sk) z1 = get_z('my_message_1') k1 = random.SystemRandom().randrange(1, N) v1, r1, s1 = sign(z1, k1, sk) z2 = get_z('my_message_2') k2 = random.SystemRandom().randrange(1, N) v2, r2, s2 = sign(z2, k2, sk) # Express d d_candidates = [(z1 * s2 * _k2 - z2 * s1 * _k1) * inv(r1 * z2 - r2 * z1, N) % N for _k1 in [k1, N - k1] for _k2 in [k2, N - k2]]
def test_valid_batch_invalid_batch(self): """Tests the squash function. That the correct hash is being used for each txn and that the batch ending state hash is being set. Basically: 1. Adds two batches, one where all the txns are valid, and one where one of the txns is invalid. 2. Run through the scheduler executor interaction as txns are processed. 3. Verify that the valid state root is obtained through the squash function. 4. Verify that correct batch statuses are set """ private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey( bitcoin.privkey_to_pubkey(private_key), "hex") context_manager = ContextManager(dict_database.DictDatabase()) squash_handler = context_manager.get_squash_handler() first_state_root = context_manager.get_first_root() scheduler = SerialScheduler(squash_handler, first_state_root) # 1) batch_signatures = [] for names in [['a', 'b'], ['invalid', 'c']]: batch_txns = [] for name in names: txn = create_transaction( name=name, private_key=private_key, public_key=public_key) batch_txns.append(txn) batch = create_batch( transactions=batch_txns, private_key=private_key, public_key=public_key) batch_signatures.append(batch.header_signature) scheduler.add_batch(batch) scheduler.finalize() # 2) sched1 = iter(scheduler) invalid_payload = hashlib.sha512('invalid'.encode()).hexdigest() while not scheduler.complete(block=False): txn_info = next(sched1) txn_header = transaction_pb2.TransactionHeader() txn_header.ParseFromString(txn_info.txn.header) inputs_or_outputs = list(txn_header.inputs) c_id = context_manager.create_context(txn_info.state_hash, inputs_or_outputs, inputs_or_outputs) if txn_header.payload_sha512 == invalid_payload: scheduler.set_transaction_execution_result( txn_info.txn.header_signature, False, c_id) else: context_manager.set(c_id, [{inputs_or_outputs[0]: 1}]) scheduler.set_transaction_execution_result( txn_info.txn.header_signature, True, c_id) sched2 = iter(scheduler) # 3) txn_info_a = next(sched2) self.assertEquals(first_state_root, txn_info_a.state_hash) txn_a_header = transaction_pb2.TransactionHeader() txn_a_header.ParseFromString(txn_info_a.txn.header) inputs_or_outputs = list(txn_a_header.inputs) address_a = inputs_or_outputs[0] c_id_a = context_manager.create_context(first_state_root, inputs_or_outputs, inputs_or_outputs) context_manager.set(c_id_a, [{address_a: 1}]) state_root2 = context_manager.commit_context([c_id_a], virtual=False) txn_info_b = next(sched2) self.assertEquals(txn_info_b.state_hash, state_root2) txn_b_header = transaction_pb2.TransactionHeader() txn_b_header.ParseFromString(txn_info_b.txn.header) inputs_or_outputs = list(txn_b_header.inputs) address_b = inputs_or_outputs[0] c_id_b = context_manager.create_context(state_root2, inputs_or_outputs, inputs_or_outputs) context_manager.set(c_id_b, [{address_b: 1}]) state_root3 = context_manager.commit_context([c_id_b], virtual=False) txn_infoInvalid = next(sched2) self.assertEquals(txn_infoInvalid.state_hash, state_root3) txn_info_c = next(sched2) self.assertEquals(txn_info_c.state_hash, state_root3) # 4) batch1_result = scheduler.get_batch_execution_result( batch_signatures[0]) self.assertTrue(batch1_result.is_valid) self.assertEquals(batch1_result.state_hash, state_root3) batch2_result = scheduler.get_batch_execution_result( batch_signatures[1]) self.assertFalse(batch2_result.is_valid) self.assertIsNone(batch2_result.state_hash)
import bitcoin valid_private_key = False while not valid_private_key: private_key = bitcoin.random_key() decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.N print "Private Key (hex) is: ", private_key print "private Key (decimal) is: ", decoded_private_key wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif') print "Private Key (WIF) is: ", wif_encoded_private_key compressed_private_key = private_key + '01' print "Private Key Compressed (hex) is: ", compressed_private_key wif_compressed_private_key = bitcoin.encode_privkey( bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif') print "Public Private Key (WIF-Compressed) is: ", wif_compressed_private_key public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) print "Public Key (x,y) coordinates is: ", public_key hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex') print "Public Key (hex) is: ", hex_encoded_public_key (public_key_x, public_key_y) = public_key if (public_key_y % 2) == 0: compressed_prefix = '02' else:
#example 4-5 import bitcoin #generate a random private key valid_private_key = False while not valid_private_key: #generate a random private key in Hex new_private_key_hex = bitcoin.random_key() #convert the hex key to decimal #this could potentially be acheived using the native python function int(x,16) where x is a Hex string private_key_decimal = bitcoin.decode_privkey(new_private_key_hex, 'hex') #checking to see if private key does not exceed the following very large number: # 115792089237316195423570985008687907852837564279074904382605163141518161494337 if private_key_decimal > 0 and private_key_decimal < bitcoin.N: valid_private_key = True print(valid_private_key) print("The new private key (Hex) is:", new_private_key_hex)
def generate_wallet_address(): my_private_key = random_key() my_public_key = privtopub(my_private_key) return pubtoaddr(my_public_key)
def test_valid_batch_invalid_batch(self): """Tests the squash function. That the correct hash is being used for each txn and that the batch ending state hash is being set. Basically: 1. Adds two batches, one where all the txns are valid, and one where one of the txns is invalid. 2. Run through the scheduler executor interaction as txns are processed. 3. Verify that the valid state root is obtained through the squash function. 4. Verify that correct batch statuses are set """ private_key = bitcoin.random_key() public_key = bitcoin.encode_pubkey( bitcoin.privkey_to_pubkey(private_key), "hex") context_manager = ContextManager(dict_database.DictDatabase()) squash_handler = context_manager.get_squash_handler() first_state_root = context_manager.get_first_root() scheduler = SerialScheduler(squash_handler, first_state_root) # 1) batch_signatures = [] for names in [['a', 'b'], ['invalid', 'c']]: batch_txns = [] for name in names: txn = create_transaction( name=name, private_key=private_key, public_key=public_key) batch_txns.append(txn) batch = create_batch( transactions=batch_txns, private_key=private_key, public_key=public_key) batch_signatures.append(batch.signature) scheduler.add_batch(batch) scheduler.finalize() # 2) sched1 = iter(scheduler) invalid_payload = hashlib.sha512('invalid'.encode()).hexdigest() while not scheduler.complete(): txn_info = next(sched1) txn_header = transaction_pb2.TransactionHeader() txn_header.ParseFromString(txn_info.txn.header) inputs_or_outputs = list(txn_header.inputs) c_id = context_manager.create_context(txn_info.state_hash, inputs_or_outputs, inputs_or_outputs) if txn_header.payload_sha512 == invalid_payload: scheduler.set_status(txn_info.txn.signature, False, c_id) else: context_manager.set(c_id, [{inputs_or_outputs[0]: 1}]) scheduler.set_status(txn_info.txn.signature, True, c_id) sched2 = iter(scheduler) # 3) txn_info_a = next(sched2) self.assertEquals(first_state_root, txn_info_a.state_hash) txn_a_header = transaction_pb2.TransactionHeader() txn_a_header.ParseFromString(txn_info_a.txn.header) inputs_or_outputs = list(txn_a_header.inputs) address_a = inputs_or_outputs[0] c_id_a = context_manager.create_context(first_state_root, inputs_or_outputs, inputs_or_outputs) context_manager.set(c_id_a, [{address_a: 1}]) state_root2 = context_manager.commit_context([c_id_a], virtual=False) txn_info_b = next(sched2) self.assertEquals(txn_info_b.state_hash, state_root2) txn_b_header = transaction_pb2.TransactionHeader() txn_b_header.ParseFromString(txn_info_b.txn.header) inputs_or_outputs = list(txn_b_header.inputs) address_b = inputs_or_outputs[0] c_id_b = context_manager.create_context(state_root2, inputs_or_outputs, inputs_or_outputs) context_manager.set(c_id_b, [{address_b: 1}]) state_root3 = context_manager.commit_context([c_id_b], virtual=False) txn_infoInvalid = next(sched2) self.assertEquals(txn_infoInvalid.state_hash, state_root3) txn_info_c = next(sched2) self.assertEquals(txn_info_c.state_hash, state_root3) # 4) batch1_status = scheduler.batch_status(batch_signatures[0]) self.assertTrue(batch1_status.valid) self.assertEquals(batch1_status.state_hash, state_root3) batch2_status = scheduler.batch_status(batch_signatures[1]) self.assertFalse(batch2_status.valid) self.assertIsNone(batch2_status.state_hash)
def test__get_message_prefix(): test_addr = bitcoin.privtoaddr(bitcoin.random_key()) prefix = messaging._get_message_prefix(test_addr) assert prefix == 'a'
from bitcoin import random_key, privtopub, pubtoaddr my_private_key = random_key() print('Bitcoin PRIVATE key = ' + my_private_key) my_public_key = privtopub(my_private_key) print('Bitcoin Public key = ' + my_public_key) my_bitcoin_address = pubtoaddr(my_public_key) print('Bitcoin ADDRESS = ' + my_bitcoin_address)
def create_addr(): priv = bit.random_key() pub = bit.privtopub(priv) addr = bit.pubtoaddr(pub) return [addr, priv]
NB_RELAY_NODES = 2 def AES_encrypt(msg, key): aes = pyaes.AESModeOfOperationCTR(key[2:34]) return aes.encrypt(str(msg)) def AES_decrypt(msg, key): aes = pyaes.AESModeOfOperationCTR(key[2:34]) return aes.decrypt(msg) ################################################################################ ############################## Initialization ############################## ################################################################################ # Generate a pair of keys for the user user_sk = bitcoin.random_key() user_pk = bitcoin.privtopub(user_sk) # Generate a pair of keys for nodes assert NB_RELAY_NODES > 0 relayNodes = list() for i in range(NB_RELAY_NODES): secret = bitcoin.random_key() relayNodes.append({ 'secret': secret, 'public': bitcoin.privtopub(secret) }) exitNode_sk = bitcoin.random_key() exitNode_pk = bitcoin.privtopub(exitNode_sk) ################################################################################