def cli_receive(filename): wif_privkey = raw_input("Enter private key in WIF compressed format: ") try: privkey = btc.from_wif_privkey(wif_privkey, vbyte=get_p2pk_vbyte()) except: print("Could not parse WIF privkey, quitting.") return amount = raw_input("Enter amount of utxo being spent, in satoshis: ") valid_coinjoins = scan_for_coinjoins(privkey, int(amount), filename) if not valid_coinjoins: print("Found no valid coinjoins") return for vc in valid_coinjoins: addr, priv, tx = vc print("Found signable coinjoin with destination address: ", addr) #TODO find a more sensible file naming fn = btc.txhash(tx) + ".txt" with open(fn, "wb") as f: f.write("SNICKER output file for receiver\n" "================================\n") f.write("The serialized transaction in hex:\n") f.write(tx + "\n") f.write("YOUR DESTINATION: " + addr + "\n") f.write("PRIVATE KEY FOR THIS DESTINATION ADDRESS:\n") f.write( btc.wif_compressed_privkey(priv, vbyte=get_p2pk_vbyte()) + "\n") f.write("The decoded transaction:\n") f.write(pformat(btc.deserialize(tx)) + "\n") print("The partially signed transaction and the private key for your " "output are stored in the file: " + fn) print( "Pass the transaction hex to `signrawtransaction` in Bitcoin Core " "or similar if you wish to broadcast the transaction.")
def test_imported_privkey(setup_wallets): for n in ["mainnet", "testnet"]: privkey = "7d998b45c219a1e38e99e7cbd312ef67f77a455a9b50c730c27f02c6f730dfb401" jm_single().config.set("BLOCKCHAIN", "network", n) password = "******" password_key = bitcoin.bin_dbl_sha256(password) wifprivkey = bitcoin.wif_compressed_privkey(privkey, get_p2pk_vbyte()) #mainnet is "L1RrrnXkcKut5DEMwtDthjwRcTTwED36thyL1DebVrKuwvohjMNi" #to verify use from_wif_privkey and privkey_to_address if n == "mainnet": iaddr = "1LDsjB43N2NAQ1Vbc2xyHca4iBBciN8iwC" else: iaddr = "mzjq2E92B3oRB7yDKbwM7XnPaAnKfRERw2" privkey_bin = bitcoin.from_wif_privkey( wifprivkey, vbyte=get_p2pk_vbyte()).decode('hex')[:-1] encrypted_privkey = encryptData(password_key, privkey_bin) encrypted_privkey_bad = encryptData(password_key, privkey_bin[:6]) walletdir = "wallets" testwalletname = "test" + n pathtowallet = os.path.join(walletdir, testwalletname) seed = bitcoin.sha256("\xaa" * 64)[:32] encrypted_seed = encryptData(password_key, seed.decode('hex')) timestamp = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") for ep in [encrypted_privkey, encrypted_privkey_bad]: walletfilejson = { 'creator': 'joinmarket project', 'creation_time': timestamp, 'encrypted_seed': encrypted_seed.encode('hex'), 'network': n, 'index_cache': [[0, 0]] * 5, 'imported_keys': [{ 'encrypted_privkey': ep.encode('hex'), 'mixdepth': 0 }] } walletfile = json.dumps(walletfilejson) if not os.path.exists(walletdir): os.makedirs(walletdir) with open(pathtowallet, "wb") as f: f.write(walletfile) if ep == encrypted_privkey_bad: with pytest.raises(Exception) as e_info: Wallet(testwalletname, password, 5, 6, False, False) continue newwallet = Wallet(testwalletname, password, 5, 6, False, False) assert newwallet.seed == seed #test accessing the key from the addr assert newwallet.get_key_from_addr( iaddr) == bitcoin.from_wif_privkey(wifprivkey, vbyte=get_p2pk_vbyte()) if n == "testnet": jm_single().bc_interface.sync_wallet(newwallet) load_program_config()
def test_wif_privkeys_invalid(): #first try to create wif privkey from key of wrong length bad_privs = [b'\x01\x02' * 17] #some silly private key but > 33 bytes #next try to create wif with correct length but wrong compression byte bad_privs.append(b'\x07' * 32 + b'\x02') for priv in bad_privs: with pytest.raises(Exception) as e_info: fake_wif = btc.wif_compressed_privkey( binascii.hexlify(priv).decode('ascii')) #Create a wif with wrong length bad_wif1 = btc.bin_to_b58check(b'\x01\x02' * 34, b'\x80') #Create a wif with wrong compression byte bad_wif2 = btc.bin_to_b58check(b'\x07' * 33, b'\x80') for bw in [bad_wif1, bad_wif2]: with pytest.raises(Exception) as e_info: fake_priv = btc.from_wif_privkey(bw) #Some invalid b58 from bitcoin repo; #none of these are valid as any kind of key or address with open(os.path.join(testdir, "base58_keys_invalid.json"), "r") as f: json_data = f.read() invalid_key_list = json.loads(json_data) for k in invalid_key_list: bad_key = k[0] for netval in ["mainnet", "testnet"]: #if using pytest -s ; sanity check to see what's actually being tested print('testing this key: ' + bad_key) #should throw exception with pytest.raises(Exception) as e_info: from_wif_key = btc.from_wif_privkey( bad_key, btc.get_version_byte(bad_key)) #in case the b58 check encoding is valid, we should #also check if the leading version byte is in the #expected set, and throw an error if not. if chr(btc.get_version_byte(bad_key)) not in b'\x80\xef': raise Exception("Invalid version byte")
def test_blockr_sync(setup_blockr, net, seed, gaplimit, showprivkey, method): jm_single().config.set("BLOCKCHAIN", "network", net) wallet = Wallet(seed, None, max_mix_depth=5) sync_wallet(wallet) #copy pasted from wallet-tool; some boiled down form of #this should really be in wallet.py in the joinmarket module. def cus_print(s): print s total_balance = 0 for m in range(wallet.max_mix_depth): cus_print('mixing depth %d m/0/%d/' % (m, m)) balance_depth = 0 for forchange in [0, 1]: cus_print(' ' + ('external' if forchange == 0 else 'internal') + ' addresses m/0/%d/%d/' % (m, forchange)) for k in range(wallet.index[m][forchange] + gaplimit): addr = wallet.get_addr(m, forchange, k) balance = 0.0 for addrvalue in wallet.unspent.values(): if addr == addrvalue['address']: balance += addrvalue['value'] balance_depth += balance used = ('used' if k < wallet.index[m][forchange] else ' new') if showprivkey: privkey = btc.wif_compressed_privkey( wallet.get_key(m, forchange, k), get_p2pk_vbyte()) else: privkey = '' if (method == 'displayall' or balance > 0 or (used == ' new' and forchange == 0)): cus_print( ' m/0/%d/%d/%03d %-35s%s %.8f btc %s' % (m, forchange, k, addr, used, balance / 1e8, privkey)) total_balance += balance_depth print('for mixdepth=%d balance=%.8fbtc' % (m, balance_depth / 1e8)) assert total_balance == 96085297
def new_wallet_from_data(data, file_name): print("Creating new wallet file.") new_pw = cli_get_wallet_passphrase_check() if new_pw is False: return False storage = Storage(file_name, create=True, password=new_pw) wallet_cls = get_wallet_cls() kwdata = { 'entropy': data['entropy'], 'timestamp': data.get('creation_time'), 'max_mixdepth': get_max_mixdepth(data) } if 'entropy_ext' in data: kwdata['entropy_extension'] = data['entropy_ext'] wallet_cls.initialize(storage, data['network'], **kwdata) wallet = wallet_cls(storage) if 'index_cache' in data: for md, indices in enumerate(data['index_cache']): wallet.set_next_index(md, 0, indices[0], force=True) wallet.set_next_index(md, 1, indices[1], force=True) if 'imported' in data: for md in data['imported']: for privkey in data['imported'][md]: privkey += b'\x01' wif = wif_compressed_privkey(hexlify(privkey).decode('ascii')) wallet.import_private_key(md, wif) wallet.save() wallet.close() return True
break if method not in noscan_methods: # if nothing was configured, we override bitcoind's options so that # unconfirmed balance is included in the wallet display by default if 'listunspent_args' not in cs_single().config.options('POLICY'): cs_single().config.set('POLICY','listunspent_args', '[0]') sync_wallet(wallet, fast=options.fastsync) if method == 'showutxos': unsp = {} if options.showprivkey: for u, av in wallet.unspent.iteritems(): addr = av['address'] key = wallet.get_key_from_addr(addr) wifkey = btc.wif_compressed_privkey(key, vbyte=get_p2pk_vbyte()) unsp[u] = {'address': av['address'], 'value': av['value'], 'privkey': wifkey} else: unsp = wallet.unspent print(json.dumps(unsp, indent=4)) sys.exit(0) if method == 'display' or method == 'displayall' or method == 'summary': def cus_print(s): if method != 'summary': print(s) total_balance = 0 for m in range(wallet.max_mix_depth):