def rootkey_from_seed(seed, network): if network == 'bitcoin' or network == 'ethereum': xprv = BIP32Key.fromEntropy(seed).ExtendedKey() elif network == 'bitcoin-testnet': xprv = BIP32Key.fromEntropy(seed, testnet=True).ExtendedKey() else: print("network should not be" + network) sys.exit( "Wrong Network : should be ethereum or bitcoin or bitcoin-testnet!" ) rootkey = BIP32Key.fromExtendedKey(xprv) return rootkey
def generate(cls, xprv=None, prv=None, seed=None, child=None, username=None): mnemonic = Mnemonic('english') # generate 12 word mnemonic seed if not seed and not xprv and not prv: seed = mnemonic.generate(256) private_key = None if seed: # create bitcoin wallet entropy = mnemonic.to_entropy(seed) key = BIP32Key.fromEntropy(entropy) private_key = key.PrivateKey().hex() extended_key = key.ExtendedKey() else: raise Exception('No Seed') if prv: private_key = PrivateKey.from_hex(bytes.fromhex(prv)).to_hex() extended_key = '' if xprv: key = BIP32Key.fromExtendedKey(xprv) private_key = key.PrivateKey().hex() extended_key = key.ExtendedKey() if xprv and child: for x in child: key = key.ChildKey(int(x)) private_key = key.PrivateKey().hex() if not private_key: raise Exception('No key') return cls({ "seed": seed or '', "xprv": extended_key or '', "private_key": private_key, "wif": cls.generate_wif(private_key), "public_key": PublicKey.from_point(key.K.pubkey.point.x(), key.K.pubkey.point.y()).format().hex(), "address": str(key.Address()), "serve_host": "0.0.0.0", "serve_port": 8000, "use_pnp": True, "ssl": False, "origin": '', "polling": 0, "post_peer": False, # "public_ip": "", # TODO "peer_host": "", "peer_port": 8000, "web_server_host": "0.0.0.0", "web_server_port": 5000, "peer": "http://localhost:8000", "callbackurl": "http://0.0.0.0:5000/create-relationship", "fcm_key": "", "database": "yadacoin", "site_database": "yadacoinsite", "mongodb_host": "localhost", "mixpanel": "", "username": username or '', "network": "mainnet" })
def test_transfer_ggo_no_src_ggo(self): key = BIP32Key.fromEntropy( "the_valid_key_that_owns_the_specific_ggo".encode()) ggo_src = generate_address(AddressPrefix.GGO, key.PublicKey()) ggo_dst = 'ggonextc37509b1de4a7f9f1c59e0efc2ed285e7c96c29d5271edd8b4c2714e3c8979c' context = MockContext(states={}) payload = class_schema(SplitGGORequest)().dumps( SplitGGORequest(origin=ggo_src, parts=[ SplitGGOPart(address="split1_add", amount=10), SplitGGOPart(address="split2_add", amount=20) ])).encode('utf8') transaction = self.create_fake_transaction(inputs=[ggo_src, ggo_dst], outputs=[ggo_src, ggo_dst], payload=payload, key=key) with self.assertRaises(InvalidTransaction) as invalid_transaction: SplitGGOTransactionHandler().apply(transaction, context) self.assertEqual(str(invalid_transaction.exception), f'Address "{ggo_src}" does not contain a valid GGO.')
def derive_address(list_of_mnemonics): """ :param list_of_mnemonics: list of unique mnemonic phrases with valid checksums """ addresses = {} print("\nDeriving addresses") for possibility in list_of_mnemonics: str_poss = ' '.join(possibility) seed = bip39.seed_from_mnemonic( str_poss, "") # Converting mnemonic to BIP39 Seed key = BIP32Key.fromEntropy(seed) # Converting to BIP32 Root Key account_number = 0 # This variable can be changed to attain a different derivation path i = 0 # This variable can be changed to attain a different derivation path # For the following account derivation `BIP32_HARDEN` can be simply removed to access unhardened addresses addr = (key.ChildKey(49 + BIP32_HARDEN).ChildKey( 0 + BIP32_HARDEN).ChildKey(account_number + BIP32_HARDEN).ChildKey( 0).ChildKey(i).P2WPKHoP2SHAddress()) addresses[addr] = str_poss print(f"\n{len(addresses)} addresses derived.") for address in addresses: print(f"Checking address {address}") if blockcypher.get_total_num_transactions(address) > 0: print( f'\nThe correct address is: {address}\nThe correct mnemonic is: \n{addresses[addr]}' ) quit()
def getPrivateKey(self, seed, account, change, address_index): m = BIP32Key.fromEntropy(Mnemonic.to_seed(seed)) m = m.ChildKey(44 + BIP32_HARDEN) m = m.ChildKey(195 + BIP32_HARDEN) m = m.ChildKey(account + BIP32_HARDEN) m = m.ChildKey(change) m = m.ChildKey(address_index) return m
def init_from_entropy(self, entropy): entropy = entropy.encode() key = BIP32Key.fromEntropy(entropy, public=False) self.private_key = key.PrivateKey() self.public_key = key.PublicKey() self.uncompressed_public_key = decode_hex( Bip32Keys.to_uncompressed_public_key(self.get_public_key()))[0]
def process(data, lst, mnemo): code = mnemo.to_mnemonic(unhexlify(data)) _seed = Mnemonic.to_seed(code, passphrase='TREZOR') xprv = BIP32Key.fromEntropy(_seed).ExtendedKey() _seed = b2h(_seed) print('input : %s (%d bits)' % (data, len(data) * 4)) print('mnemonic : %s (%d words)' % (code, len(code.split(' ')))) print('seed : %s (%d bits)' % (_seed, len(_seed) * 4)) print('xprv : %s\n' % xprv) lst.append((data, code, _seed, xprv))
def process(data, lst): code = mnemo.to_mnemonic(unhexlify(data)).decode() seed = Mnemonic.to_seed(code, passphrase='TREZOR') xprv = BIP32Key.fromEntropy(seed).ExtendedKey() seed = b2h(seed) print('input : %s (%d bits)' % (data, len(data) * 4)) print('mnemonic : %s (%d words)' % (code, len(code.split(' ')))) print('seed : %s (%d bits)' % (seed, len(seed) * 4)) print('xprv : %s' % xprv) print() lst.append((data, code, seed, xprv))
def process(data, lst): code = mnemo.to_mnemonic(unhexlify(data)) seed = Mnemonic.to_seed(code, passphrase="TREZOR") xprv = BIP32Key.fromEntropy(seed).ExtendedKey() seed = b2h(seed) print("input : %s (%d bits)" % (data, len(data) * 4)) print("mnemonic : %s (%d words)" % (code, len(code.split(" ")))) print("seed : %s (%d bits)" % (seed, len(seed) * 4)) print("xprv : %s" % xprv) print() lst.append((data, code, seed, xprv))
def to_private_key(word): ''' get private key from word! ''' #generate seed from mnemonic word by mnemonic package m = mnemonic.Mnemonic("english") #xprv=m.to_hd_master_key(m.to_seed(words)) ;the same with BIP32Key.fromEntropy(seed) seed = m.to_seed(word) #generate extended private key(xprv) from seed key = BIP32Key.fromEntropy(seed) xprv = BIP32Key.fromEntropy(seed).ExtendedKey() # redefined key with extended private key key = BIP32Key.fromExtendedKey(xprv) #get the first account private for derivation path m/44'/60'/0' x=key.ChildKey(44 + BIP32_HARDEN) \ .ChildKey(60 + BIP32_HARDEN) \ .ChildKey(0 + BIP32_HARDEN) \ .ChildKey(0) \ .ChildKey(0) \ .PrivateKey().hex() return x
def test__KeyGenerator__set_key_for_user_from_entropy(): # Arrange entropy = b'SomethingVeryRandomWithAMinimumLengthWhichIDontQuiteRememberRightNow' user = Mock() # Act KeyGenerator.set_key_for_user_from_entropy(user, entropy) # Assert assert user.master_extended_key == BIP32Key.fromEntropy( entropy).ExtendedKey()
def test_transfer_ggo_not_authorized(self): key_owner = BIP32Key.fromEntropy( "the_valid_key_that_owns_the_specific_ggo".encode()) key_criminal = BIP32Key.fromEntropy( "this_key_should_not_be_authorized".encode()) ggo_src = generate_address(AddressPrefix.GGO, key_owner.PublicKey()) ggo_dst = 'ggonextc37509b1de4a7f9f1c59e0efc2ed285e7c96c29d5271edd8b4c2714e3c8979c' ggo = GGO.get_schema().dumps( GGO(origin= 'meaaaa1c37509b1de4a7f9f1c59e0efc2ed285e7c96c29d5271edd8b4c2714e3c8979c', amount=30, begin=datetime(2020, 1, 1, 12, tzinfo=timezone.utc), end=datetime(2020, 1, 1, 13, tzinfo=timezone.utc), tech_type='T12412', fuel_type='F010101', sector='DK1', next=None)).encode('utf8') context = MockContext(states={ggo_src: ggo}) payload = class_schema(SplitGGORequest)().dumps( SplitGGORequest(origin=ggo_src, parts=[ SplitGGOPart(address="split1_add", amount=10), SplitGGOPart(address="split2_add", amount=20) ])).encode('utf8') transaction = self.create_fake_transaction(inputs=[ggo_src, ggo_dst], outputs=[ggo_src, ggo_dst], payload=payload, key=key_criminal) with self.assertRaises(InvalidTransaction) as invalid_transaction: SplitGGOTransactionHandler().apply(transaction, context) self.assertEqual(str(invalid_transaction.exception), 'Invalid key for GGO')
def __init__(self, entropy): # todo: init from private key entropy = entropy.encode() self.decode_hex = codecs.getdecoder("hex_codec") self.encode_hex = codecs.getencoder("hex_codec") key = BIP32Key.fromEntropy(entropy, public=False) private_key = key.PrivateKey() public_key = key.PublicKey() wif = key.WalletImportFormat() sk = SigningKey.from_string(string=private_key, curve=ecdsa.SECP256k1, hashfunc=sha256) vk = sk.get_verifying_key() #print(public_key) output = sha256(public_key).digest() #print(binascii.hexlify(output)) ripemd160 = hashlib.new('ripemd160') ripemd160.update(output) output = binascii.hexlify(ripemd160.digest()) #print(output) output = b'3A' + output # 3A is magic byte extended_ripmd160 = output #print(output) output = self.decode_hex(output)[0] output = sha256(output).digest() #print(binascii.hexlify(output)) output = sha256(output).hexdigest().encode() #print(binascii.hexlify(output)) checksum = output[:8] #print(checksum) output = extended_ripmd160 + checksum #print(output) output = self.decode_hex(output)[0] output = base58check.b58encode(output) #print(output) self.wif = wif self.private_key = private_key self.public_key = public_key self.uncompressed_public_key = vk.to_string() self.qtum_address = output
def main(): import binascii import sys if len(sys.argv) > 1: data = sys.argv[1] else: data = sys.stdin.readline().strip() data = binascii.unhexlify(data) m = Mnemonic('english') # example mnemonic print("Mnemonic generated from entropy " + m.to_mnemonic(data)) from bip32utils import BIP32Key print("\nExample mnemonic: " + "profit hood vibrant fiscal survey traffic quality rely soap fury helmet once") seed = m.to_seed("profit hood vibrant fiscal survey traffic quality rely soap fury helmet once") print("Seed " + seed.encode('hex')) key = BIP32Key.fromEntropy(seed) xprv = BIP32Key.fromEntropy(seed).ExtendedKey() print("Extended private key is " + xprv) # redefined key with extended private key key = BIP32Key.fromExtendedKey(xprv) from bip32utils import BIP32_HARDEN # first address for derivation path m/44'/0'/0' print(key.ChildKey(44 + BIP32_HARDEN) \ .ChildKey(0 + BIP32_HARDEN) \ .ChildKey(0 + BIP32_HARDEN) \ .ChildKey(0) \ .ChildKey(0) \ .Address()) # second address for derivation path m/44'/0'/0' print(key.ChildKey(44 + BIP32_HARDEN) \ .ChildKey(0 + BIP32_HARDEN) \ .ChildKey(0 + BIP32_HARDEN) \ .ChildKey(0) \ .ChildKey(1) \ .Address())
def generate_wallet() -> dict: mnemo = Mnemonic("english") data = generate_random_wallet_input() code = mnemo.to_mnemonic(unhexlify(data)) seed = Mnemonic.to_seed(code, passphrase="LURA") xprv = BIP32Key.fromEntropy(seed).ExtendedKey() priv = BIP32Key.fromEntropy(seed).PrivateKey() wif = BIP32Key.fromEntropy(seed).PublicKey() signing_key = ecdsa.SigningKey.from_string(priv, curve=ecdsa.SECP256k1) verifying_key = signing_key.get_verifying_key() wallet = { "input": data, "mnemonic": code, "seed": seed.hex(), "xprv": xprv, "private_key": priv.hex(), "public_key": wif.hex(), "verifying_key": verifying_key.to_string().hex(), "address": pubkey_to_address(wif), } return wallet
def entropy2prvhex(entropy, derivation_path): """Entropy Bytes -> Private Key Hex""" from bip32utils import BIP32Key, BIP32_HARDEN assert isinstance(derivation_path, str), 'str_ should be str' path_list = derivation_path.split('/') assert path_list[0] == 'm', 'Derivation path should start with char "m"' xkey = BIP32Key.fromEntropy(entropy).ExtendedKey() key = BIP32Key.fromExtendedKey(xkey) for path in path_list[1:]: if path[-1] == "'": key = key.ChildKey(int(path[:-1]) + BIP32_HARDEN) else: key = key.ChildKey(int(path)) return key.PrivateKey().hex()
def child_keys(mnemonic, index): seed = mnemoniclib.Mnemonic.to_seed(mnemonic) rootkey = BIP32Key.fromEntropy(seed) childkey_object = rootkey.ChildKey(44 + BIP32_HARDEN)\ .ChildKey(index + BIP32_HARDEN)\ .ChildKey(index + BIP32_HARDEN)\ .ChildKey(index).ChildKey(index) return { #"private_key": childkey_object.WalletImportFormat(), "private_key": childkey_object.PrivateKey().hex(), "public_key": childkey_object.PublicKey().hex(), "address": childkey_object.Address() }
def __init__( self, mnemonic: str = None, account: int = 0, index: int = 0, coin_type: int = LUNA_COIN_TYPE, ): if mnemonic is None: mnemonic = Mnemonic("english").generate(256) seed = Mnemonic("english").to_seed(mnemonic) root = BIP32Key.fromEntropy(seed) # derive from hdpath child = (root.ChildKey(44 + BIP32_HARDEN).ChildKey( coin_type + BIP32_HARDEN).ChildKey(account + BIP32_HARDEN).ChildKey(0).ChildKey(index)) super().__init__(child.PrivateKey()) self.mnemonic = mnemonic self.account = account self.index = index
def create_wallet(self, backup_key): # check for existing wallet result = yield self.bitgo.wallet() for wallet in result["wallets"]: if result["wallets"][wallet]["label"] == "sputnik": raise MultiSigException("Wallet already exists.") # create a new key # TODO: allow testnet key = BIP32Key.fromEntropy("".join(map(chr, [random.getrandbits(8) for i in range(32)])), public=False) # TODO: save private key private = key.ExtendedKey(private=True, encoded=True) user_key = key.ExtendedKey(private=False, encoded=True) # create a new bitgo key result = yield self.bitgo.keychain("bitgo") bitgo_key = result["xpub"] # create the wallet keychains = [{"xpub":user_key}, {"xpub":backup_key}, {"xpub":bitgo_key}] yield self.bitgo.wallet(label="sputnik", m=2, n=3, keychains=keychains)
def generate(cls, xprv=None, prv=None, seed=None, child=None, username=None, mongodb_host=None, db_name=None): mnemonic = Mnemonic('english') # generate 12 word mnemonic seed if not seed and not xprv and not prv: seed = mnemonic.generate(256) private_key = None if seed: # create new wallet entropy = mnemonic.to_entropy(seed) key = BIP32Key.fromEntropy(entropy) private_key = key.PrivateKey().hex() extended_key = key.ExtendedKey() public_key = PublicKey.from_point( key.K.pubkey.point.x(), key.K.pubkey.point.y()).format().hex() address = str(key.Address()) if prv: key = PrivateKey.from_hex(prv) private_key = key.to_hex() extended_key = '' public_key = key.public_key.format().hex() address = str( P2PKHBitcoinAddress.from_pubkey(bytes.fromhex(public_key))) if xprv: key = BIP32Key.fromExtendedKey(xprv) private_key = key.PrivateKey().hex() extended_key = key.ExtendedKey() public_key = PublicKey.from_point( key.K.pubkey.point.x(), key.K.pubkey.point.y()).format().hex() address = str(key.Address()) if xprv and child: for x in child: key = key.ChildKey(int(x)) private_key = key.PrivateKey().hex() public_key = PublicKey.from_point( key.K.pubkey.point.x(), key.K.pubkey.point.y()).format().hex() address = str(key.Address()) if not private_key: raise Exception('No key') try: u = UPnP(None, None, 200, 0) u.discover() u.selectigd() peer_host = u.externalipaddress() except: try: import urllib.request peer_host = urllib.request.urlopen( 'https://ident.me').read().decode('utf8') except: peer_host = '' return cls({ "modes": ['node', 'web', 'pool'], "root_app": '', "seed": seed or '', "xprv": extended_key or '', "private_key": private_key, "wif": cls.generate_wif(private_key), "public_key": public_key, "address": address, "api_whitelist": [], "serve_host": "0.0.0.0", "serve_port": 8001, "use_pnp": False, "ssl": False, "origin": '', "sia_api_key": '', "post_peer": False, "peer_host": peer_host, "peer_port": 8000, "peer_type": "user", "peer": "http://localhost:8000", "callbackurl": "http://0.0.0.0:8001/create-relationship", "jwt_public_key": None, "fcm_key": "", "database": db_name or "yadacoin", "site_database": db_name + "site" if db_name else "yadacoinsite", "mongodb_host": mongodb_host or "localhost", "mixpanel": "", "username": username or '', "network": "mainnet", "wallet_host_port": 'http://localhost:8001', "credits_per_share": 5, "shares_required": False, "pool_payout": False, "pool_take": .01, "payout_frequency": 6 })
from bip32utils import BIP32Key, BIP32_HARDEN from mnemonic import Mnemonic # EOS https://github.com/satoshilabs/slips/blob/master/slip-0044.md coin_type = 194 # 0: receive, 1: change path = 0 # index index = 0 seed = 'pride pride pride pride pride pride pride pride pride pride pride pride' m = BIP32Key.fromEntropy(Mnemonic.to_seed(seed)) m = m.ChildKey(44 + BIP32_HARDEN) m = m.ChildKey(coin_type + BIP32_HARDEN) m = m.ChildKey(0 + BIP32_HARDEN) m = m.ChildKey(path) m = m.ChildKey(index) print m.dump()
def from_entropy(cls, entropy, *args, **kwargs): return cls(BIP32Key.fromEntropy(entropy), *args, **kwargs)
def setUp(self): self.master_key = BIP32Key.fromEntropy( "bfdgafgaertaehtaha43514r<aefag".encode()) context = create_context('secp256k1') self.crypto = CryptoFactory(context)
return ethereum_data(account) if __name__ == '__main__': m = Mnemonic('english') words = m.generate(strength=256) print(words) seed = m.to_seed(words) print("************") print("Seed " + seed.hex()) #key = BIP32Key.fromEntropy(seed) print("******************Test Bitcoin********************") globalkey = BIP32Key.fromEntropy(seed) root = globalkey.ExtendedKey() print("Root Key is " + root) key = BIP32Key.fromExtendedKey(root) bitcoinkey = key.ChildKey(44 + BIP32_HARDEN) \ .ChildKey(0 + BIP32_HARDEN) \ .ChildKey(0 + BIP32_HARDEN) AccountExtendedPrivateKey = bitcoinkey.ExtendedKey() print("Account Extended Private Key is " + AccountExtendedPrivateKey) AccountExtendedPublicKey = bitcoinkey.ExtendedKey(private=False) print("Account Extended Public Key is " + AccountExtendedPublicKey) bitcoinaccount = bitcoinkey.ChildKey(0) BIP32ExtendedPrivateKey = bitcoinaccount.ExtendedKey() print("BIP32 Extended Private Key is : " + BIP32ExtendedPrivateKey) BIP32ExtendedPublicKey = bitcoinaccount.ExtendedKey(private=False) print("BIP32 Extended Public Key is : " + BIP32ExtendedPublicKey)
return ethereum_data(account) if __name__ == '__main__': m = Mnemonic('english') words = m.generate(strength=256) print(words) seed = m.to_seed(words) print("************") print("Seed " + seed.hex()) #key = BIP32Key.fromEntropy(seed) print("******************Test Bitcoin********************") xprv = BIP32Key.fromEntropy(seed).ExtendedKey() print("Root Key is " + xprv) key = BIP32Key.fromExtendedKey(xprv) bitcoin0 = key.ChildKey(44 + BIP32_HARDEN) \ .ChildKey(0 + BIP32_HARDEN) \ .ChildKey(0 + BIP32_HARDEN) \ .ChildKey(0) \ .ChildKey(0) print("first private key") print(bitcoin0.WalletImportFormat()) print("first address") print(bitcoin0.Address()) print("******************Test Bitcoin Testnet********************") xprv = BIP32Key.fromEntropy(seed, testnet=True).ExtendedKey()
def derive_root(seed: bytes) -> BIP32Key: return BIP32Key.fromEntropy(seed)
def set_key_for_user_from_entropy(user, entropy): """ :param origin.auth.User user: :param bytes entropy: """ KeyGenerator.set_key_for_user(user, BIP32Key.fromEntropy(entropy))
def test_integration(self): issuer_key = BIP32Key.fromEntropy( "this_will_be_the_issuers_main_key_entropy".encode()) user_1_masterkey = BIP32Key.fromEntropy( "this_will_be_user_one_who_has_the_production_device".encode()) user_2_masterkey = BIP32Key.fromEntropy( "this_will_be_user_two_who_has_the_production_device".encode()) # Accounts is always 0.0 user_1_account = user_1_masterkey.ChildKey(0).ChildKey(0) # Meatering points is always 1.n user_1_meter_42 = user_1_masterkey.ChildKey(1).ChildKey(42) # Accounts is always 0.0 user_2_account = user_2_masterkey.ChildKey(0).ChildKey(0) # Meatering points is always 1.n user_2_meter_5 = user_2_masterkey.ChildKey(1).ChildKey(5) with DockerCompose("./test") as compose: time.sleep(5) host = compose.get_service_host('rest-api', 8008) port = compose.get_service_port('rest-api', 8008) url = f'http://{host}:{port}' ledger = Ledger(url) # ----------- Publish and Issue ----------- measurement_prod_key = user_1_meter_42.ChildKey(26429040) measurement_prod_address = generate_address( AddressPrefix.MEASUREMENT, measurement_prod_key.PublicKey()) measurement_prod_request = PublishMeasurementRequest( address=measurement_prod_address, begin=datetime(2020, 4, 1, 12, tzinfo=timezone.utc), end=datetime(2020, 4, 1, 13, tzinfo=timezone.utc), sector='DK1', type=MeasurementType.PRODUCTION, amount=100) measurement_con_key = user_2_meter_5.ChildKey(26429040) measurement_con_address = generate_address( AddressPrefix.MEASUREMENT, measurement_con_key.PublicKey()) measurement_con_request = PublishMeasurementRequest( address=measurement_con_address, begin=datetime(2020, 4, 1, 12, tzinfo=timezone.utc), end=datetime(2020, 4, 1, 13, tzinfo=timezone.utc), sector='DK1', type=MeasurementType.CONSUMPTION, amount=50) ggo_issue_address = generate_address( AddressPrefix.GGO, measurement_prod_key.PublicKey()) ggo_issue_request = IssueGGORequest( measurement_address=measurement_prod_address, ggo_address=ggo_issue_address, tech_type='T124124', fuel_type='F12412') batch = Batch(issuer_key.PrivateKey()) batch.add_request(measurement_prod_request) batch.add_request(measurement_con_request) batch.add_request(ggo_issue_request) handle = ledger.execute_batch(batch) self.wait_for_commit(ledger, handle) # ----------- Trade the GGO ----------- split_request = SplitGGORequest( source_private_key=measurement_prod_key.PrivateKey(), source_address=ggo_issue_address, parts=[ SplitGGOPart(address=generate_address( AddressPrefix.GGO, user_1_account.ChildKey(0).PublicKey()), amount=50), SplitGGOPart(address=generate_address( AddressPrefix.GGO, user_1_account.ChildKey(1).PublicKey()), amount=25), SplitGGOPart(address=generate_address( AddressPrefix.GGO, user_2_account.ChildKey(0).PublicKey()), amount=25) ]) batch = Batch(user_1_masterkey.PrivateKey()) batch.add_request(split_request) handle = ledger.execute_batch(batch) self.wait_for_commit(ledger, handle) # ----------- Trade the GGO ----------- transfer_request = TransferGGORequest( source_private_key=user_1_account.ChildKey(1).PrivateKey(), source_address=generate_address( AddressPrefix.GGO, user_1_account.ChildKey(1).PublicKey()), destination_address=generate_address( AddressPrefix.GGO, user_2_account.ChildKey(1).PublicKey()), ) batch = Batch(user_1_masterkey.PrivateKey()) batch.add_request(transfer_request) handle = ledger.execute_batch(batch) self.wait_for_commit(ledger, handle) # ----------- Retire GGO ----------- settlement_address = generate_address( AddressPrefix.SETTLEMENT, measurement_con_key.PublicKey()) retire_request = RetireGGORequest( settlement_address=settlement_address, measurement_address=measurement_con_address, measurement_private_key=measurement_con_key.PrivateKey(), parts=[ RetireGGOPart( address=generate_address( AddressPrefix.GGO, user_2_account.ChildKey(0).PublicKey()), private_key=user_2_account.ChildKey(0).PrivateKey()), RetireGGOPart( address=generate_address( AddressPrefix.GGO, user_2_account.ChildKey(1).PublicKey()), private_key=user_2_account.ChildKey(1).PrivateKey()) ]) batch = Batch(user_2_masterkey.PrivateKey()) batch.add_request(retire_request) handle = ledger.execute_batch(batch) self.wait_for_commit(ledger, handle)
def test_transfer_ggo_success(self): key = BIP32Key.fromEntropy( "the_valid_key_that_owns_the_specific_ggo".encode()) ggo_src = generate_address(AddressPrefix.GGO, key.PublicKey()) ggo = GGO.get_schema().dumps( GGO(origin= 'meaaaa1c37509b1de4a7f9f1c59e0efc2ed285e7c96c29d5271edd8b4c2714e3c8979c', amount=80, begin=datetime(2020, 1, 1, 12, tzinfo=timezone.utc), end=datetime(2020, 1, 1, 13, tzinfo=timezone.utc), tech_type='T12412', fuel_type='F010101', sector='DK1', next=None, emissions={ "co2": { "value": 1113342.14, "unit": "g/Wh", }, "so2": { "value": 9764446, "unit": "g/Wh", }, })).encode('utf8') context = MockContext(states={ggo_src: ggo}) payload = class_schema(SplitGGORequest)().dumps( SplitGGORequest(origin=ggo_src, parts=[ SplitGGOPart(address="split1_add", amount=10), SplitGGOPart(address="split2_add", amount=20), SplitGGOPart(address="split3_add", amount=50) ])).encode('utf8') transaction = self.create_fake_transaction( inputs=[ggo_src, "split1_add", "split2_add", "split3_add"], outputs=[ggo_src, "split1_add", "split2_add", "split3_add"], payload=payload, key=key) SplitGGOTransactionHandler().apply(transaction, context) self.assertIn(ggo_src, context.states) obj = json.loads(context.states[ggo_src].decode('utf8')) self.assertEqual(len(obj), 9) self.assertEqual( obj['origin'], 'meaaaa1c37509b1de4a7f9f1c59e0efc2ed285e7c96c29d5271edd8b4c2714e3c8979c' ) self.assertEqual(obj['amount'], 80) self.assertEqual(obj['begin'], '2020-01-01T12:00:00+00:00') self.assertEqual(obj['end'], '2020-01-01T13:00:00+00:00') self.assertEqual(obj['sector'], 'DK1') self.assertEqual(obj['tech_type'], 'T12412') self.assertEqual(obj['fuel_type'], 'F010101') self.assertEqual( obj['emissions'], { "co2": { "value": 1113342.14, "unit": "g/Wh", }, "so2": { "value": 9764446, "unit": "g/Wh", }, }) self.assertEqual(obj['next']['action'], GGOAction.SPLIT.name) self.assertEqual(len(obj['next']['addresses']), 3) self.assertEqual(obj['next']['addresses'][0], 'split1_add') self.assertEqual(obj['next']['addresses'][1], 'split2_add') self.assertEqual(obj['next']['addresses'][2], 'split3_add') obj = json.loads(context.states['split1_add'].decode('utf8')) self.assertEqual(len(obj), 9) self.assertEqual(obj['origin'], ggo_src) self.assertEqual(obj['amount'], 10) self.assertEqual(obj['begin'], '2020-01-01T12:00:00+00:00') self.assertEqual(obj['end'], '2020-01-01T13:00:00+00:00') self.assertEqual(obj['sector'], 'DK1') self.assertEqual(obj['tech_type'], 'T12412') self.assertEqual(obj['fuel_type'], 'F010101') self.assertEqual( obj['emissions'], { "co2": { "value": 1113342.14, "unit": "g/Wh", }, "so2": { "value": 9764446, "unit": "g/Wh", }, }) self.assertEqual(obj['next'], None) obj = json.loads(context.states['split2_add'].decode('utf8')) self.assertEqual(len(obj), 9) self.assertEqual(obj['origin'], ggo_src) self.assertEqual(obj['amount'], 20) self.assertEqual(obj['begin'], '2020-01-01T12:00:00+00:00') self.assertEqual(obj['end'], '2020-01-01T13:00:00+00:00') self.assertEqual(obj['sector'], 'DK1') self.assertEqual(obj['tech_type'], 'T12412') self.assertEqual(obj['fuel_type'], 'F010101') self.assertEqual( obj['emissions'], { "co2": { "value": 1113342.14, "unit": "g/Wh", }, "so2": { "value": 9764446, "unit": "g/Wh", }, }) self.assertEqual(obj['next'], None) obj = json.loads(context.states['split3_add'].decode('utf8')) self.assertEqual(len(obj), 9) self.assertEqual(obj['origin'], ggo_src) self.assertEqual(obj['amount'], 50) self.assertEqual(obj['begin'], '2020-01-01T12:00:00+00:00') self.assertEqual(obj['end'], '2020-01-01T13:00:00+00:00') self.assertEqual(obj['sector'], 'DK1') self.assertEqual(obj['tech_type'], 'T12412') self.assertEqual(obj['fuel_type'], 'F010101') self.assertEqual( obj['emissions'], { "co2": { "value": 1113342.14, "unit": "g/Wh", }, "so2": { "value": 9764446, "unit": "g/Wh", }, }) self.assertEqual(obj['next'], None)
# Opening valid possibilities file, produced by main.py script with open("valid_possibilities.out.txt", "r") as f: accounts_to_check = json.loads(f.read()) # If you need to skip use this # accounts_to_check = accounts_to_check[94:] print(f"Loaded {len(accounts_to_check)} accounts. Running checks...") addresses = {} print("Deriving addresses") for possibility in accounts_to_check: str_poss = ' '.join(possibility) seed = bip39.seed_from_mnemonic(str_poss, "") # Converting mnemonic to BIP39 Seed key = BIP32Key.fromEntropy(seed) # Converting to BIP32 Root Key account_number = 0 # This variable can be changed to attain a different derivation path i = 0 # This variable can be changed to attain a different derivation path # For the following account derivation, `BIP32_HARDEN` can be simply removed to access unhardened addresses addr = key.ChildKey(49 + BIP32_HARDEN) \ .ChildKey(0 + BIP32_HARDEN) \ .ChildKey(account_number + BIP32_HARDEN) \ .ChildKey(0) \ .ChildKey(i) \ .P2WPKHoP2SHAddress() addresses[addr] = str_poss print(f"{len(addresses)} addresses derived.") for address in addresses: print(f"Checking address {address}") if blockcypher.get_total_num_transactions(address) > 0:
def setUp(self): master_key = BIP32Key.fromEntropy( "bfdgafgaertaehtaha43514r<aefag".encode()) context = create_context('secp256k1') self.key_1 = master_key.ChildKey(1) self.false_key = master_key.ChildKey(1241).ChildKey(1241) self.false_signer = CryptoFactory(context).new_signer( PrivateKey.from_bytes(self.false_key.PrivateKey())) self.mea_prod_1_key = master_key.ChildKey(1).ChildKey(1) self.mea_prod_1_add = generate_address(AddressPrefix.MEASUREMENT, self.mea_prod_1_key.PublicKey()) self.mea_prod_1 = Measurement.get_schema().dumps( Measurement(amount=25, type=MeasurementType.PRODUCTION, begin=datetime(2020, 1, 1, 12, tzinfo=timezone.utc), end=datetime(2020, 1, 1, 13, tzinfo=timezone.utc), sector='DK1')).encode('utf8') self.mea_prod_2_add = 'mea_prod_2_add' self.mea_prod_3_add = 'mea_prod_3_add' self.mea_con_1_key = master_key.ChildKey(3).ChildKey(1) self.mea_con_1_add = generate_address(AddressPrefix.MEASUREMENT, self.mea_con_1_key.PublicKey()) self.mea_con_1 = Measurement.get_schema().dumps( Measurement(amount=150, type=MeasurementType.CONSUMPTION, begin=datetime(2020, 1, 1, 12, tzinfo=timezone.utc), end=datetime(2020, 1, 1, 13, tzinfo=timezone.utc), sector='DK1')).encode('utf8') self.mea_con_2_key = master_key.ChildKey(3).ChildKey(2) self.mea_con_2_add = generate_address(AddressPrefix.MEASUREMENT, self.mea_con_2_key.PublicKey()) self.mea_con_2 = Measurement.get_schema().dumps( Measurement(amount=15, type=MeasurementType.CONSUMPTION, begin=datetime(2020, 1, 1, 12, tzinfo=timezone.utc), end=datetime(2020, 1, 1, 13, tzinfo=timezone.utc), sector='DK1')).encode('utf8') self.ggo_1_key = master_key.ChildKey(2).ChildKey(1) self.ggo_1_signer = CryptoFactory(context).new_signer( PrivateKey.from_bytes(self.ggo_1_key.PrivateKey())) self.ggo_1_add = generate_address(AddressPrefix.GGO, self.ggo_1_key.PublicKey()) self.ggo_1 = GGO.get_schema().dumps( GGO(origin=self.mea_prod_1_add, amount=10, begin=datetime(2020, 1, 1, 12, tzinfo=timezone.utc), end=datetime(2020, 1, 1, 13, tzinfo=timezone.utc), tech_type='T12412', fuel_type='F010101', sector='DK1', next=None, emissions={ "co2": { "value": 1113342.14, "unit": "g/Wh", }, "so2": { "value": 9764446, "unit": "g/Wh", }, })).encode('utf8') self.ggo_2_key = master_key.ChildKey(2).ChildKey(2) self.ggo_2_signer = CryptoFactory(context).new_signer( PrivateKey.from_bytes(self.ggo_2_key.PrivateKey())) self.ggo_2_add = generate_address(AddressPrefix.GGO, self.ggo_2_key.PublicKey()) self.ggo_2 = GGO.get_schema().dumps( GGO(origin=self.mea_prod_2_add, amount=25, begin=datetime(2020, 1, 1, 12, tzinfo=timezone.utc), end=datetime(2020, 1, 1, 13, tzinfo=timezone.utc), tech_type='T12412', fuel_type='F010101', sector='DK1', next=None, emissions={ "co2": { "value": 1113342.14, "unit": "g/Wh", }, "so2": { "value": 9764446, "unit": "g/Wh", }, })).encode('utf8') self.ggo_3_key = master_key.ChildKey(2).ChildKey(3) self.ggo_3_signer = CryptoFactory(context).new_signer( PrivateKey.from_bytes(self.ggo_3_key.PrivateKey())) self.ggo_3_add = generate_address(AddressPrefix.GGO, self.ggo_3_key.PublicKey()) self.ggo_3 = GGO.get_schema().dumps( GGO(origin=self.mea_prod_3_add, amount=15, begin=datetime(2020, 1, 1, 12, tzinfo=timezone.utc), end=datetime(2020, 1, 1, 13, tzinfo=timezone.utc), tech_type='T12412', fuel_type='F010101', sector='DK1', next=None, emissions={ "co2": { "value": 1113342.14, "unit": "g/Wh", }, "so2": { "value": 9764446, "unit": "g/Wh", }, })).encode('utf8') self.ggo_DK2_key = master_key.ChildKey(2).ChildKey(3) self.ggo_DK2_signer = CryptoFactory(context).new_signer( PrivateKey.from_bytes(self.ggo_DK2_key.PrivateKey())) self.ggo_DK2_add = generate_address(AddressPrefix.GGO, self.ggo_DK2_key.PublicKey()) self.ggo_DK2 = GGO.get_schema().dumps( GGO(origin=self.mea_prod_3_add, amount=15, begin=datetime(2020, 1, 1, 12, tzinfo=timezone.utc), end=datetime(2020, 1, 1, 13, tzinfo=timezone.utc), tech_type='T12412', fuel_type='F010101', sector='DK2', next=None, emissions={ "co2": { "value": 1113342.14, "unit": "g/Wh", }, "so2": { "value": 9764446, "unit": "g/Wh", }, })).encode('utf8') self.ggo_other_time_key = master_key.ChildKey(2).ChildKey(3) self.ggo_other_time_signer = CryptoFactory(context).new_signer( PrivateKey.from_bytes(self.ggo_other_time_key.PrivateKey())) self.ggo_other_time_add = generate_address( AddressPrefix.GGO, self.ggo_other_time_key.PublicKey()) self.ggo_other_time = GGO.get_schema().dumps( GGO(origin=self.mea_prod_3_add, amount=15, begin=datetime(2020, 1, 1, 13, tzinfo=timezone.utc), end=datetime(2020, 1, 1, 14, tzinfo=timezone.utc), tech_type='T12412', fuel_type='F010101', sector='DK1', next=None, emissions={ "co2": { "value": 1113342.14, "unit": "g/Wh", }, "so2": { "value": 9764446, "unit": "g/Wh", }, })).encode('utf8') self.ggo_used_key = master_key.ChildKey(2).ChildKey(54687) self.ggo_used_signer = CryptoFactory(context).new_signer( PrivateKey.from_bytes(self.ggo_used_key.PrivateKey())) self.ggo_used_add = generate_address(AddressPrefix.GGO, self.ggo_used_key.PublicKey()) self.ggo_used = GGO.get_schema().dumps( GGO(origin='mea_prod_used_add', amount=15, begin=datetime(2020, 1, 1, 12, tzinfo=timezone.utc), end=datetime(2020, 1, 1, 13, tzinfo=timezone.utc), tech_type='T12412', fuel_type='F010101', sector='DK1', next=GGONext(action=GGOAction.RETIRE, addresses=['mea_con_used_add']), emissions={ "co2": { "value": 1113342.14, "unit": "g/Wh", }, "so2": { "value": 9764446, "unit": "g/Wh", }, })).encode('utf8') self.ggo_used_multiple_key = master_key.ChildKey(2).ChildKey(54687) self.ggo_used_multiple_signer = CryptoFactory(context).new_signer( PrivateKey.from_bytes(self.ggo_used_multiple_key.PrivateKey())) self.ggo_used_multiple_add = generate_address( AddressPrefix.GGO, self.ggo_used_multiple_key.PublicKey()) self.ggo_used_multiple = GGO.get_schema().dumps( GGO(origin='mea_prod_used_add', amount=15, begin=datetime(2020, 1, 1, 12, tzinfo=timezone.utc), end=datetime(2020, 1, 1, 13, tzinfo=timezone.utc), tech_type='T12412', fuel_type='F010101', sector='DK1', next=GGONext( action=GGOAction.RETIRE, addresses=['mea_con_used_add', 'mea_con_used_add2']), emissions={ "co2": { "value": 1113342.14, "unit": "g/Wh", }, "so2": { "value": 9764446, "unit": "g/Wh", }, })).encode('utf8') self.ggo_transfered_key = master_key.ChildKey(2).ChildKey(54688) self.ggo_transfered_signer = CryptoFactory(context).new_signer( PrivateKey.from_bytes(self.ggo_transfered_key.PrivateKey())) self.ggo_transfered_add = generate_address( AddressPrefix.GGO, self.ggo_transfered_key.PublicKey()) self.ggo_transfered = GGO.get_schema().dumps( GGO(origin='mea_prod_used_add', amount=15, begin=datetime(2020, 1, 1, 12, tzinfo=timezone.utc), end=datetime(2020, 1, 1, 13, tzinfo=timezone.utc), tech_type='T12412', fuel_type='F010101', sector='DK1', next=GGONext(action=GGOAction.TRANSFER, addresses=['mea_con_used_add']), emissions={ "co2": { "value": 1113342.14, "unit": "g/Wh", }, "so2": { "value": 9764446, "unit": "g/Wh", }, })).encode('utf8')