def guess_currency_from_address(address): """ Given a crypto address, find which currency it likely belongs to. Raises an exception if it can't find a match. Raises exception if address is invalid. """ if is_py2: fixer = lambda x: int(x.encode('hex'), 16) else: fixer = lambda x: x # does nothing first_byte = fixer(b58decode_check(address)[0]) double_first_byte = fixer(b58decode_check(address)[:2]) hits = [] for currency, data in crypto_data.items(): if hasattr(data, 'get'): # skip incomplete data listings version = data.get('address_version_byte', None) if version is not None and version in [double_first_byte, first_byte]: hits.append([currency, data['name']]) if hits: return hits raise ValueError("Unknown Currency with first byte: %s" % first_byte)
def _flush(client, wallet, amount=None, payout_address=None): """ Flushes current off-chain balance to the blockchain Args: client (two1.server.rest_client.TwentyOneRestClient) an object for sending authenticated requests to the TwentyOne backend. wallet (two1.wallet.Wallet): a user's wallet instance amount (int): The amount to be flushed. Should be more than 10k amount (string): The address to flush the Bitcoins to Raises: ServerRequestError: if server returns an error code other than 401 """ if payout_address: try: # check whether this is a valid Bitcoin address base58.b58decode_check(payout_address) except ValueError: logger.error(uxstring.UxString.flush_invalid_address) return try: response = client.flush_earnings(amount=amount, payout_address=payout_address) if response.ok: success_msg = uxstring.UxString.flush_success.format(wallet.current_address) logger.info(success_msg) except exceptions.ServerRequestError as ex: if ex.status_code == 401: logger.info(uxstring.UxString.flush_insufficient_earnings) elif ex.status_code == 400 and ex.data.get("detail") == "TO500": logger.info(uxstring.UxString.flush_not_enough_earnings.format(amount), fg="red") else: raise ex
def cmd_worker_new(): # Validate JSON body w/ API params try: body = request.data.decode('utf-8') in_obj = json.loads(body) except: return ("JSON Decode failed", 400, {'Content-Type':'text/plain'}) # Validate JSON object basics try: if (not 'payout_addr' in in_obj or not 'pkh' in in_obj): return ("Missing name/pkh", 400, {'Content-Type':'text/plain'}) pkh = in_obj['pkh'] payout_addr = in_obj['payout_addr'] base58.b58decode_check(pkh) base58.b58decode_check(payout_addr) except: return ("JSON validation exception", 400, {'Content-Type':'text/plain'}) # Add worker to database. Rely on db to filter out dups. try: db.worker_add(pkh, payout_addr) except: return ("DB Exception - add worker", 400, {'Content-Type':'text/plain'}) body = json.dumps(True, indent=2) return (body, 200, { 'Content-length': len(body), 'Content-type': 'application/json', })
def privatekey_to_int(privatekey): if whether_compressed_privatekey(privatekey): hex32private = base58.b58decode_check(privatekey)[1:-1] else: hex32private = base58.b58decode_check(privatekey)[1:] str_bin = ''.join([bin(x)[2:].rjust(8, '0') for x in hex32private]) number = int(str_bin,2) return number
def _flush(client, wallet, machine_auth, amount=None, payout_address=None, silent=False, to_primary=False): """ Flushes current off-chain buffer to the blockchain. Args: client (two1.server.rest_client.TwentyOneRestClient) an object for sending authenticated requests to the TwentyOne backend. wallet (two1.wallet.Wallet): a user's wallet instance. amount (int): The amount to be flushed. Should be more than 10k. payout_address (string): The address to flush the Bitcoins to. silent (boolean): If True, disables the confirmation prompt. to_primary (boolean): If True, flushes to the primary wallet. Raises: ServerRequestError: if server returns an error code other than 401. """ # check the payout address if payout_address: try: base58.b58decode_check(payout_address) except ValueError: logger.error(uxstring.UxString.flush_invalid_address) return # select the wallet and the associated payout address for the flush all_wallets = client.list_wallets() wallet_payout_address, wallet_name = _select_flush_wallet(client, machine_auth, payout_address, all_wallets, to_primary) # ask user for confirmation if not silent: # if the user has not specified a payout_address then the buffer will be flushed to the # primary wallet. is_local = payout_address is None should_continue = _show_confirmation(machine_auth, amount, all_wallets, wallet_payout_address, wallet_name, to_primary, is_local) if not should_continue: return # perform flush try: response = client.flush_earnings(amount=amount, payout_address=wallet_payout_address) if response.ok: success_msg = uxstring.UxString.flush_success.format(wallet_payout_address) logger.info(success_msg) except exceptions.ServerRequestError as ex: if ex.status_code == 401: logger.info(ex.message) elif ex.status_code == 400 and ex.data.get("error") == "TO500": logger.info(uxstring.UxString.flush_not_enough_earnings.format(amount), fg="red") elif ex.status_code == 403 and ex.data.get("error") == "social_account_required_to_flush": logger.info("You must connect a social account with your 21.co account before you can flush.", fg="red") else: raise ex
def cmd_task_new(): # Validate JSON body w/ API params try: body = request.data.decode('utf-8') in_obj = json.loads(body) except: return ("JSON Decode failed", 400, {'Content-Type':'text/plain'}) # Validate JSON object basics try: if (not 'pkh' in in_obj or not 'summary' in in_obj or not 'image' in in_obj or not 'image_ctype' in in_obj or not 'template' in in_obj or not 'min_workers' in in_obj or not 'reward' in in_obj): return ("Missing params", 400, {'Content-Type':'text/plain'}) pkh = in_obj['pkh'] summary = in_obj['summary'] image = binascii.unhexlify(in_obj['image']) image_ctype = in_obj['image_ctype'] template = in_obj['template'] min_workers = int(in_obj['min_workers']) reward = int(in_obj['reward']) base58.b58decode_check(pkh) except: return ("JSON validation exception", 400, {'Content-Type':'text/plain'}) # Check work template wt = worktmp.WorkTemplate() wt.set(template) if not wt.valid(): return ("JSON template validation failed", 400, {'Content-Type':'text/plain'}) # Generate unique id time_str = str(int(time.time())) md = hashlib.sha256() md.update(time_str.encode('utf-8')) md.update(body.encode('utf-8')) id = md.hexdigest() # Add worker to database. Rely on db to filter out dups. try: template_json = json.dumps(template) db.task_add(id, summary, pkh, image, image_ctype, template_json, min_workers, reward) except: return ("DB Exception - add task", 400, {'Content-Type':'text/plain'}) return (id, 200, { 'Content-length': len(body), 'Content-type': 'text/plain', })
def updatewhitelist(arg): if (not os.path.isfile(arg)): # arg is not a file, see if it is an SJCX address try: base58.b58decode_check(arg) except: raise RuntimeError( 'Invalid address given: "{0}" is not a valid SJCX address ' 'or path to whitelist file.'.format(arg)) s = Address.__table__.select().where(Address.address == arg) result = db.engine.execute(s).first() bal = app.config['MIN_SJCX_BALANCE'] if (result is not None): if (result.crowdsale_balance <= bal): db.engine.execute(Address.__table__.update().\ where(Address.id == result.id).\ values(crowdsale_balance = bal)) else: print('{0} is already in the whitelist.'.format(arg)) else: db.engine.execute(Address.__table__.insert().\ values(address=arg, crowdsale_balance=bal)) return with open(arg,'r') as f: r = csv.reader(f) next(r) updated=list() for l in r: s = Address.__table__.select().where(Address.address == l[0]) result = db.engine.execute(s).first() if (result is not None): db.engine.execute(Address.__table__.update().\ where(Address.id == result.id).\ values(crowdsale_balance=int(l[1]))) else: db.engine.execute(Address.__table__.insert().\ values(address=l[0], crowdsale_balance=l[1])) result = db.engine.execute(Address.__table__.select().\ where(Address.address == l[0])).first() updated.append(result.id) all = db.engine.execute(Address.__table__.select()).fetchall() for row in all: if (row.id not in updated): # also recursively delete all tokens associated with that address tbd_tokens = db.engine.execute(Token.__table__.select().\ where(Token.address_id == row.id)).fetchall() for t in tbd_tokens: # and all contracts associated with that address db.engine.execute(Contract.__table__.delete().\ where(Contract.token_id == t.id)) db.engine.execute(Token.__table__.delete().\ where(Token.id == t.id)) db.engine.execute(Address.__table__.delete().\ where(Address.id == row.id))
def wif_to_address(crypto, wif): if is_py2: wif_byte = int(hexlify(b58decode_check(wif)[0]), 16) else: wif_byte = b58decode_check(wif)[0] if not wif_byte == crypto_data[crypto.lower()]['private_key_prefix']: msg = 'WIF encoded with wrong prefix byte. Are you sure this is a %s address?' % crypto.upper() raise Exception(msg) address_byte = crypto_data[crypto.lower()]['address_version_byte'] return privkey_to_address(wif, address_byte)
def create_token(sjcx_address, remote_addr, message=None, signature=None): """Creates a token for the given address. Address must be in the white list of addresses. :param sjcx_address: address to use for token creation. :param remote_addr: ip address of the farmer requesting a token :param message: the message for a signature :param signature: the signature specified :returns: the token database object """ # make sure that the currnet ip has not excceeded it's token count assert_ip_allowed_one_more_token(remote_addr) # make sure the address is valid try: base58.b58decode_check(sjcx_address) except: raise InvalidParameterError( 'Invalid address given: address is not a valid SJCX address.') # confirm that sjcx_address is in the list of addresses # and meets balance requirements # for now we have a white list db_address = Address.query.filter( and_(Address.address == sjcx_address, Address.crowdsale_balance >= app.config['MIN_SJCX_BALANCE'])).\ first() if (db_address is None): raise InvalidParameterError( 'Invalid address given: address must be in whitelist.') location = get_ip_location(remote_addr) token = os.urandom(16) token_string = binascii.hexlify(token).decode('ascii') token_hash = SHA256.new(token).hexdigest()[:20] db_token = Token(token=token_string, address=db_address, ip_address=remote_addr, farmer_id=token_hash, location=location, message=message, signature=signature) db.session.add(db_token) db.session.commit() return db_token
def cmd_host_register(): # Validate JSON body w/ API params try: body = request.data.decode('utf-8') in_obj = json.loads(body) except: return ("JSON Decode failed", 400, {'Content-Type':'text/plain'}) try: if (not 'name' in in_obj): return ("Missing name", 400, {'Content-Type':'text/plain'}) name = in_obj['name'] pkh = None days = 1 if 'pkh' in in_obj: pkh = in_obj['pkh'] if 'days' in in_obj: days = int(in_obj['days']) if not valid_name(name) or days < 1 or days > 365: return ("Invalid name/days", 400, {'Content-Type':'text/plain'}) if pkh: base58.b58decode_check(pkh) if (len(pkh) < 20) or (len(pkh) > 40): return ("Invalid pkh", 400, {'Content-Type':'text/plain'}) except: return ("JSON validation exception", 400, {'Content-Type':'text/plain'}) # Validate and collect host records for updating host_records = parse_hosts(name, in_obj) if isinstance(host_records, str): return (host_records, 400, {'Content-Type':'text/plain'}) # Add to database. Rely on db to filter out dups. try: db.add_host(name, days, pkh) if len(host_records) > 0: db.update_host(name, host_records) except: return ("Host addition rejected", 400, {'Content-Type':'text/plain'}) body = json.dumps(True, indent=2) return (body, 200, { 'Content-length': len(body), 'Content-type': 'application/json', })
def coinbaseMessage(previous_output, receiver_address, my_address, private_key): receiver_hashed_pubkey= base58.b58decode_check(receiver_address)[1:].encode("hex") my_hashed_pubkey = base58.b58decode_check(my_address)[1:].encode("hex") # Transaction stuff version = struct.pack("<L", 1) lock_time = struct.pack("<L", 0) hash_code = struct.pack("<L", 1) # Transactions input tx_in_count = struct.pack("<B", 1) tx_in = {} tx_in["outpoint_hash"] = previous_output.decode('hex')[::-1] tx_in["outpoint_index"] = struct.pack("<L", 4294967295) tx_in["script"] = ("76a914%s88ac" % my_hashed_pubkey).decode("hex") tx_in["script_bytes"] = struct.pack("<B", (len(tx_in["script"]))) tx_in["sequence"] = "ffffffff".decode("hex") # Transaction output tx_out_count = struct.pack("<B", 1) tx_out = {} tx_out["value"]= struct.pack("<Q", 100000000 * 12.50033629) tx_out["pk_script"]= ("76a914%s88ac" % receiver_hashed_pubkey).decode("hex") tx_out["pk_script_bytes"]= struct.pack("<B", (len(tx_out["pk_script"]))) tx_to_sign = (version + tx_in_count + tx_in["outpoint_hash"] + tx_in["outpoint_index"] + tx_in["script_bytes"] + tx_in["script"] + tx_in["sequence"] + tx_out_count + tx_out["value"] + tx_out["pk_script_bytes"] + tx_out["pk_script"] + lock_time + hash_code) # Signing txn hashed_raw_tx = hashlib.sha256(hashlib.sha256(tx_to_sign).digest()).digest() sk = ecdsa.SigningKey.from_string(private_key.decode("hex"), curve = ecdsa.SECP256k1) vk = sk.verifying_key public_key = ('\04' + vk.to_string()).encode("hex") sign = sk.sign_digest(hashed_raw_tx, sigencode=ecdsa.util.sigencode_der) # Complete txn sigscript = sign + "\01" + struct.pack("<B", len(public_key.decode("hex"))) + public_key.decode("hex") real_tx = (version + tx_in_count + tx_in["outpoint_hash"] + tx_in["outpoint_index"] + struct.pack("<B", (len(sigscript) + 1)) + struct.pack("<B", len(sign) + 1) + sigscript + tx_in["sequence"] + tx_out_count + tx_out["value"] + tx_out["pk_script_bytes"] + tx_out["pk_script"] + lock_time) return real_tx
def decode_prv(prv_wif): if type(prv_wif) != str or not is_b58(prv_wif) or len(prv_wif) not in (51, 52): raise TypeError("expected a wif string of 51 or 52 char") try: b58decode_check(prv_wif.encode()) except: ValueError("invalid checksum") wif_decoded = b58decode_check(prv_wif.encode()) version = wif_decoded[:1] prv = int.from_bytes(wif_decoded[1:33], "big") private = PrivateKey(prv) private.set_version(version) if len(prv_wif) == 52: if wif_decoded[-1] != 1: raise TypeError("when the private key is compressed the last value must be a b'\x01'") else: private.set_uncompressed() return private
def decode_add(address_wif): if type(address_wif) != str or not is_b58(address_wif) or len(address_wif) > 34: raise TypeError("expected a wif string of 34 or less char") wif_decoded = b58decode_check(address_wif.encode()) version = wif_decoded[:1] address = Address() address.set_address(wif_decoded[1:21]) address.set_version(version) return address
def _get_bitcoin_address(self): private_key_decode = base58.b58decode_check(self.private_key) if len(private_key_decode) ==33: private_key = private_key_decode[1:] elif len(private_key_decode) ==34: private_key = private_key_decode[1:-1] else: raise Exception public_key_uncompress,public_key_compress = self._get_public_key(private_key, self.NID_secp256k1) return base58.b58encode_check(b'\x00'+self._sha256ripemd160(public_key_uncompress)), base58.b58encode_check(b'\x00'+self._sha256ripemd160(public_key_compress))
def cmd_host_register(): # Validate JSON body w/ API params try: body = request.data.decode("utf-8") in_obj = json.loads(body) except: return http400("JSON Decode failed") try: if not "name" in in_obj or not "domain" in in_obj: return http400("Missing name/domain") name = in_obj["name"] domain = in_obj["domain"] pkh = None days = 1 if "pkh" in in_obj: pkh = in_obj["pkh"] if "days" in in_obj: days = int(in_obj["days"]) if not valid_name(name) or days < 1 or days > 365: return http400("Invalid name/days") if not db.valid_domain(domain): return http404("Domain not found") if pkh: base58.b58decode_check(pkh) if (len(pkh) < 20) or (len(pkh) > 40): return http400("Invalid pkh") except: return http400("JSON validation exception") # Check against reserved host name list if reserved_name(name): return http400("Reserved name. Name not available for registration.") # Validate and collect host records for updating host_records = parse_hosts(name, domain, in_obj) if isinstance(host_records, str): return http400(host_records) return store_host(name, domain, days, pkh, host_records)
def from_b58check(key): """ Decodes a Base58Check encoded key. The encoding must conform to the description in: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#serialization-format Args: key (str): A Base58Check encoded key. Returns: HDPrivateKey or HDPublicKey: Either an HD private or public key object, depending on what was serialized. """ return HDKey.from_bytes(base58.b58decode_check(key))[0]
def prv_wif_info(): parser = ArgumentParser(description="extract all the info from a bitcoin wif string") parser.add_argument("wif_str", help="wif string, in base58", type=str) args = parser.parse_args() try: wif_decoded = b58decode_check(args.wif_str.encode()) version = wif_decoded[:1] prv = wif_decoded[1:33] compressed = len(args.wif_str) == 52 print("format\n" + ("" if compressed else "un") + "compressed") print("version prefix in hex\n" + version.hex()) print("private key in hex\n" + hex(int.from_bytes(prv, "big"))[2:]) except ValueError: print("invalid checksum")
def validateaddress(self, params): # check for [] parameter or [""] if not params or params[0] == '': raise JsonRpcError(-100, "Missing argument") isValid = False try: data = base58.b58decode_check(params[0]) if len(data) == 21 and data[0] == settings.ADDRESS_VERSION: isValid = True except Exception as e: pass return {"address": params[0], "isvalid": isValid}
def address_to_key_hash(s): """ Given a Bitcoin address decodes the version and RIPEMD-160 hash of the public key. Args: s (bytes): The Bitcoin address to decode Returns: (version, h160) (tuple): A tuple containing the version and RIPEMD-160 hash of the public key. """ n = base58.b58decode_check(s) version = n[0] h160 = n[1:] return version, h160
def decode_prv_wif(): parser = ArgumentParser(description="extract all the information from a private key in wif") parser.add_argument("wif_str", help="private key, in wif format", type=str) args = parser.parse_args() try: wif_decoded = b58decode_check(args.wif_str.encode()) version = wif_decoded[:1] prv = wif_decoded[1:33] compressed = len(args.wif_str) == 52 and wif_decoded[33:] == b'\x01' if not compressed and len(args.wif_str) != 51: raise ValueError("private key longer then expected") print("format\n" + ("" if compressed else "un") + "compressed") print("version prefix in hex\n" + version.hex()) print("private key in hex\n" + hex(int.from_bytes(prv, "big"))[2:]) except ValueError: print("invalid checksum")
def p2pkh_address_to_pubkey_hash(address): """ Takes a P2PKH address (starting with a 1, m or n symbol) and extracts its HASH160 hash (used as a public key hash). :see: https://en.bitcoin.it/wiki/List_of_address_prefixes :param address: P2PKH public address :returns: HASH160 hash of the public key """ decoded = b58decode_check(address) # check that it is a mainnet or testnet P2PKH address assert(decoded[0] in [0x00, 0x6F]) return decoded[1:] # skip version byte
def decode_prv(prv_str): if not isinstance(prv_str, str): raise TypeError("private key must be a string") lp = len(prv_str) if lp in (51, 52): # WIF if not all(c in b58digits for c in prv_str): raise TypeError("private key in WIF must use base58 char") prv_b = b58decode_check(prv_str) return prv_b[:1], int.from_bytes(prv_b[1:33], "big"), lp == 52 if lp == 66 and prv_str[:2] == "0x": prv_str = prv_str[2:] if lp <= 64: if not all(c in "0123456789abcdefABCDEF" for c in prv_str): raise TypeError("private key in hex must use hex char") return None, int(prv_str, 16), None raise ValueError("Invalid private key")
def from_wif(cls, wif, network=BitcoinMainNet): """Import a key in WIF format. WIF is Wallet Import Format. It is a base58 encoded checksummed key. See https://en.bitcoin.it/wiki/Wallet_import_format for a full description. This supports compressed WIFs - see this for an explanation: http://bitcoin.stackexchange.com/questions/7299/when-importing-private-keys-will-compressed-or-uncompressed-format-be-used # nopep8 (specifically http://bitcoin.stackexchange.com/a/7958) """ # Decode the base58 string and ensure the checksum is valid wif = ensure_str(wif) try: extended_key_bytes = base58.b58decode_check(wif) except ValueError as e: # Invalid checksum! raise ChecksumException(e) # Verify we're on the right network network_bytes = extended_key_bytes[0] # py3k interprets network_byte as an int already if not isinstance(network_bytes, six.integer_types): network_bytes = ord(network_bytes) if (network_bytes != network.SECRET_KEY): raise incompatible_network_exception_factory( network_name=network.NAME, expected_prefix=network.SECRET_KEY, given_prefix=network_bytes) # Drop the network bytes extended_key_bytes = extended_key_bytes[1:] # Check for comprssed public key # This only affects the way in which addresses are generated. compressed = False if len(extended_key_bytes) == 33: # We are supposed to use compressed form! extended_key_bytes = extended_key_bytes[:-1] compressed = True # And we should finally have a valid key return cls(long_or_int(hexlify(extended_key_bytes), 16), network, compressed=compressed)
def from_wif(privkey): # extract the secret exponent from the given coin-formatted private key private_key = "" try: extended_key_bytes = base58.b58decode_check(privkey) except ValueError as e: # Invalid checksum! raise Exception("Invalid Private Key provided. Must be in Wallet Import Format.") # Drop the network bytes extended_key_bytes = extended_key_bytes[1:] private_key = extended_key_bytes if (len(private_key) == 33): private_key = extended_key_bytes[:-1] return BlockIo.Key(private_key)
def change_version_byte(address, new_version=None, new_crypto=None): """ Convert the passed in address (or any base58 encoded string), and change the version byte to `new_version`. """ if not new_version and new_crypto: try: new_version = crypto_data[new_crypto]['address_version_byte'] except KeyError: raise CurrencyNotSupported("Unknown currency symbol: " + new_crypto) if not new_version: raise CurrencyNotSupported("Can't yet make %s addresses." % new_crypto) payload = b58decode_check(address)[1:] if is_py2: byte = chr(new_version) else: byte = bytes(chr(new_version), 'ascii') return b58encode_check(byte + payload)
def decrypt_wallet(): if "--wallet" in sys.argv: i = sys.argv.index("--wallet") + 1 wallet = sys.argv[i] else: print "Please enter your encrypted wallet." wallet = raw_input("Wallet:") if wallet[0:2] == "RK": #Wallet is unencrypted passphrase = None elif "--passphrase" in sys.argv: i = sys.argv.index("--passphrase") + 1 passphrase = sys.argv[i] else: print "Please enter your passphrase." passphrase = getpass.getpass("Passphrase:") wallet_data = base58.b58decode_check(wallet) root_key = bip38v2.decrypt_wallet(wallet_data, passphrase)[3] print "Root key:" print root_key.encode('hex')
def from_wif(privkey): # extract the secret exponent from the given coin-formatted private key private_key = "" try: extended_key_bytes = base58.b58decode_check(privkey) except ValueError as e: # Invalid checksum! raise Exception("Invalid Private Key provided. Must be in Wallet Import Format.") # is this a compressed WIF or not? is_compressed = len(hexlify(extended_key_bytes)) == 68 and hexlify(extended_key_bytes)[-2:] == "01" # Drop the network bytes extended_key_bytes = extended_key_bytes[1:] private_key = extended_key_bytes if (len(private_key) == 33): private_key = extended_key_bytes[:-1] return BlockIo.Key(private_key, None, is_compressed)
def from_wif(wif): return PrivateKey(bytearray(b58decode_check(wif)[1:-1]))
def whether_bitcoinaddress(bitcoinaddress): try: private_key_decode = base58.b58decode_check(bitcoinaddress) return True except: return False
def getBytes(tx, **options): """ Hash transaction. Args: tx (dict or Transaction): transaction object. **Options**: * `exclude_sig` *bool* - exclude signature during tx serialization. Defalut to False. * `exclude_multi_sig` *bool* - exclude signatures during tx serialization. Defalut to False. * `exclude_second_sig` *bool* - exclude second signatures during tx serialization. Defalut to False. Returns: bytes: transaction serial. """ if tx.get("version", 0x01) >= 0x02: return serialize(tx, **options) buf = BytesIO() # write type and timestamp pack("<BI", buf, (tx["type"], int(tx["timestamp"]))) # write senderPublicKey as bytes in buffer if "senderPublicKey" in tx: pack_bytes(buf, unhexlify(tx["senderPublicKey"])) # if there is a requesterPublicKey if "requesterPublicKey" in tx: pack_bytes(buf, unhexlify(tx["requesterPublicKey"])) # if there is a recipientId or tx not a second secret nor a multi # singature registration if tx.get("recipientId", False) and tx["type"] not in [1, 4]: recipientId = tx["recipientId"] recipientId = base58.b58decode_check( str(recipientId ) if not isinstance(recipientId, bytes) else recipientId) else: recipientId = b"\x00" * 21 pack_bytes(buf, recipientId) # deal with vendorField values if "vendorFieldHex" in tx: vendorField = unhexlify(tx["vendorFieldHex"]) else: value = tx.get("vendorField", b"") if not isinstance(value, bytes): value = value.encode("utf-8") vendorField = value vendorField = vendorField[:64].ljust(64, b"\x00") pack_bytes(buf, vendorField) # write amount and fee value pack("<QQ", buf, (tx.get("amount", 0), tx["fee"])) # if there is asset data if tx.get("asset", False): asset, typ = tx["asset"], tx["type"] if typ == 1 and "signature" in asset: pack_bytes(buf, unhexlify(asset["signature"]["publicKey"])) elif typ == 2 and "delegate" in asset: pack_bytes(buf, asset["delegate"]["username"].encode("utf-8")) elif typ == 3 and "votes" in asset: pack_bytes(buf, "".join(asset["votes"]).encode("utf-8")) else: raise Exception("transaction type %s not implemented" % typ) # if there is a signature if "signature" in tx and not options.get("exclude_sig", False): pack_bytes(buf, unhexlify(tx["signature"])) # if there is a second signature if not options.get("exclude_second_sig", False): if tx.get("signSignature", False): pack_bytes(buf, unhexlify(tx["signSignature"])) elif tx.get("secondSignature", False): pack_bytes(buf, unhexlify(tx["secondSignature"])) result = buf.getvalue() buf.close() return result
def hexTRONAddress(address): return base58.b58decode_check(address.encode()).encode("hex")
def wif_decode(wif_privkey): decoded_wif = b58decode_check(wif_privkey)[1:] # Compressed ? if len(decoded_wif) == 33: return decoded_wif[:-1] return decoded_wif
def check(k): try: base58.b58decode_check(k) return True except: return False
def base58_decode(encoded): if encoded[2] != '_': raise ValueError('Invalid hash') return base58.b58decode_check(encoded[3:])
def wif_to_private(self, wif): dec = base58.b58decode_check(wif) if dec[0] != 0x80: raise ValueError("Invalid network (expected mainnet)") return dec[1:]
def _base58_decode(encoded_str): """decode a base58 string to bytes""" return base58.b58decode_check(encoded_str)
def address_public_digest(address): """Convert a public Bitcoin address to its ripemd160(sha256()) digest.""" public_plain = b58decode_check(address) if not public_plain.startswith(b'\x00') or len(public_plain) != 21: raise ValueError('Invalid public key digest') return public_plain[1:]
def base58_check_decode(self, data: bytes) -> bytes: if len(data) > self._MAX_INPUT_LENGTH: raise ValueError( f"Value exceeds maximum length of {self._MAX_INPUT_LENGTH}") return base58.b58decode_check(data)
def bc_address_to_hash_160(addr): return b58decode_check(addr)[1:21]
def wif_to_hex(wif): """ Convert a WIF encded private key and return the raw hex encoded private key This function works for all bitcoin-API compatable coins. """ return hexlify(b58decode_check(wif)[1:]).upper()
def decode_new_address(address, chain_id): address_data = address[3:] hex_address = base58.b58decode_check(address_data) return hex_address.hex()[-40:]
# node3_addr = node3.getnewaddress(address_type="bech32") node1.generatetoaddress(250, node1_addr) # node2.generatetoaddress(250, node2_addr) # node3.generate(2) balance1 = node1.getbalance() print('Balance node 1:', balance1) # balance2 = node2.getbalance() # print('Balance node 2:', balance2) node1_priv = node1.dumpprivkey(node1_addr) print("Node1 key base58: {}".format(node1_priv)) node1_key_bytes = base58.b58decode_check(node1_priv)[1:-1] print("Node1 key: {}".format(node1_key_bytes.hex())) node1_key = ECKey() node1_key.set(node1_key_bytes, True) # Spending key key0 = ECKey() key0.generate(compressed=True) key0_bytes = b'\xef' + key0.get_bytes() + b'\x01' key0_wif = str(base58.b58encode_check(key0_bytes), "ascii") addr0 = key_to_p2pkh(key0.get_pubkey().get_bytes()) print("key0 bytes: {}".format(key0_bytes.hex()))
def address_hex(address): return base58.b58decode_check(address).hex().upper()
# Alice -> Bob (5BTC) -> Charlie import struct import base58 import hashlib import ecdsa Bob_addr = "1NWzVg38ggPoVGAG2VWt6ktdWMaV6S1pJK" bob_hashed_pubkey = base58.b58decode_check(Bob_addr)[1:].encode("hex") Bob_private_key = "CF933A6C602069F1CBC85990DF087714D7E86DF0D0E48398B7D8953E1F03534A" prv_txid = "84d813beb51c3a12cb5d0bb18c6c15062453d476de24cb2f943ca6e20115d85c" Charlie_adr = "17X4s8JdSdLxFyraNUDBzgmnSNeZpjm42g" charlie_hashed_pubkey = base58.b58decode_check(Charlie_adr)[1:].encode("hex") # Bob sends 0.001 BTC to Charlie and he sends 0.0005 BTC back to himself (change) and the remainder of 0.0005 BTC will be given to the miner as a fee # 1. raw tx # 2. raw tx and sign that tx using my private key (this is the only way to prove that I'm Bob) # 3. raw tx and signature in order to create the real tx class raw_tx: version = struct.pack("<L", 1) tx_in_count = struct.pack("<B", 1) tx_in = {} #TEMP tx_out_count = struct.pack("<B", 2) tx_out1 = {} #TEMP tx_out2 = {} #TEMP
def _flush(client, wallet, machine_auth, amount=None, payout_address=None, silent=False, to_primary=False): """ Flushes current off-chain buffer to the blockchain. Args: client (two1.server.rest_client.TwentyOneRestClient) an object for sending authenticated requests to the TwentyOne backend. wallet (two1.wallet.Wallet): a user's wallet instance. amount (int): The amount to be flushed. Should be more than 10k. payout_address (string): The address to flush the Bitcoins to. silent (boolean): If True, disables the confirmation prompt. to_primary (boolean): If True, flushes to the primary wallet. Raises: ServerRequestError: if server returns an error code other than 401. """ # check the payout address if payout_address: try: base58.b58decode_check(payout_address) except ValueError: logger.error(uxstring.UxString.flush_invalid_address) return # select the wallet and the associated payout address for the flush all_wallets = client.list_wallets() wallet_payout_address, wallet_name = _select_flush_wallet( client, machine_auth, payout_address, all_wallets, to_primary) # ask user for confirmation if not silent: # if the user has not specified a payout_address then the buffer will be flushed to the # primary wallet. is_local = payout_address is None should_continue = _show_confirmation(machine_auth, amount, all_wallets, wallet_payout_address, wallet_name, to_primary, is_local) if not should_continue: return # perform flush try: response = client.flush_earnings(amount=amount, payout_address=wallet_payout_address) if response.ok: success_msg = uxstring.UxString.flush_success.format( wallet_payout_address) logger.info(success_msg) except exceptions.ServerRequestError as ex: if ex.status_code == 401: logger.info(uxstring.UxString.flush_insufficient_earnings) elif ex.status_code == 400 and ex.data.get("error") == "TO500": logger.info( uxstring.UxString.flush_not_enough_earnings.format(amount), fg="red") elif ex.status_code == 403 and ex.data.get( "error") == "social_account_required_to_flush": logger.info( "You must connect a social account with your 21.co account before you can flush.", fg="red") else: raise ex
def test_check_str(): data = 'hello world' out = b58encode_check(data) assert_that(out, equal_to(b'3vQB7B6MrGQZaxCuFg4oh')) back = b58decode_check(out) assert_that(back, b'hello world')
def to_zip32_key_bytes(key_str): decoded = base58.b58decode_check(key_str) return decoded[13:]
def address_to_pubkey_hash(address): return base58.b58decode_check(address)[1:]
def serialize(self): self.bytes_data += write_bit64(self.transaction['amount']) self.bytes_data += write_bit32(self.transaction.get('expiration', 0)) recipientId = hexlify(b58decode_check(self.transaction['recipientId'])) self.bytes_data += write_high(recipientId) return self.bytes_data
def deserialize(cls, key, network="bitcoin_testnet"): """Load the ExtendedBip32Key from a hex key. The key consists of * 4 byte version bytes (network key) * 1 byte depth: - 0x00 for master nodes, - 0x01 for level-1 descendants, .... * 4 byte fingerprint of the parent's key (0x00000000 if master key) * 4 byte child number. This is the number i in x_i = x_{par}/i, with x_i the key being serialized. This is encoded in MSB order. (0x00000000 if master key) * 32 bytes: the chain code * 33 bytes: the public key or private key data (0x02 + X or 0x03 + X for public keys, 0x00 + k for private keys) (Note that this also supports 0x04 + X + Y uncompressed points, but this is totally non-standard and this library won't even generate such data.) """ network = Wallet.get_network(network) if len(key) in [78, (78 + 32)]: # we have a byte array, so pass pass else: key = ensure_bytes(key) if len(key) in [78 * 2, (78 + 32) * 2]: # we have a hexlified non-base58 key, continue! key = unhexlify(key) elif len(key) == 111: # We have a base58 encoded string key = base58.b58decode_check(key) # Now that we double checkd the values, convert back to bytes because # they're easier to slice version, depth, parent_fingerprint, child, chain_code, key_data = ( key[:4], key[4], key[5:9], key[9:13], key[13:45], key[45:]) version_long = long_or_int(hexlify(version), 16) exponent = None pubkey = None point_type = key_data[0] if not isinstance(point_type, six.integer_types): point_type = ord(point_type) if point_type == 0: # Private key if version_long != network.EXT_SECRET_KEY: raise incompatible_network_exception_factory( network.NAME, network.EXT_SECRET_KEY, version) exponent = key_data[1:] elif point_type in [2, 3, 4]: # Compressed public coordinates if version_long != network.EXT_PUBLIC_KEY: raise incompatible_network_exception_factory( network.NAME, network.EXT_PUBLIC_KEY, version) pubkey = PublicKey.from_hex_key(key_data, network=network) # Even though this was generated from a compressed pubkey, we # want to store it as an uncompressed pubkey pubkey.compressed = False else: raise ValueError("Invalid key_data prefix, got %s" % point_type) def l(byte_seq): if byte_seq is None: return byte_seq elif isinstance(byte_seq, six.integer_types): return byte_seq return long_or_int(hexlify(byte_seq), 16) return cls(depth=l(depth), parent_fingerprint=l(parent_fingerprint), child_number=l(child), chain_code=l(chain_code), private_exponent=l(exponent), public_key=pubkey, network=network)
def whether_compressed_privatekey(privatekey): private_key_decode = base58.b58decode_check(privatekey) if len(private_key_decode) == 33: return False elif len(private_key_decode) == 34: return True
def checkAddress(address): if base58.b58decode_check( address.encode("utf-8") if not PY3 and not isinstance(address, bytes) else address): return address
def wif2privkey(self): return base58.b58decode_check(self.privkey_wif)[1:]
def getSignableTxn(parsed): first, sig, pub, rest = parsed inputAddr = base58.b58decode_check(keyUtils.pubKeyToAddr(pub)) return first + "1976a914" + inputAddr.encode( 'hex') + "88ac" + rest + "01000000"
def hashfs_put(hexstr): # decode hex string param hexstr = hexstr.lower() try: hash = binascii.unhexlify(hexstr) except TypeError: abort(400) if len(hash) != 32: abort(400) # get sqlite handle connection = HASHFS_DB cursor = connection.cursor() # get content-length clen_str = request.headers.get('content-length') if clen_str is None: abort(400) clen = int(request.headers.get('content-length')) if clen < 1 or clen > (100 * 1000 * 1000): abort(400) # do we have room for this new data? free_space = hashfs_free_space(cursor) if free_space < clen: # attempt to remove old, expired data (if any) hashfs_expire_data(cursor, clen) # do we have room for this new data, pass #2 free_space = hashfs_free_space(cursor) # TODO: is there a better HTTP status? if free_space < clen: abort(500) # get content-type ctype = request.headers.get('content-type') if blank_re.match(ctype): ctype = 'application/octet-stream' # note public key hash, if provided pkh = request.headers.get('x-hashfs-pkh') if not pkh is None: if len(pkh) < 32 or len(pkh) > 35: abort(400) try: base58.b58decode_check(pkh) except: abort(400) # check file existence; if it exists, no need to proceed further # create dir1/dir2 hierarchy if need be filename = make_hashfs_fn(hexstr, True) if filename is None: abort(500) if os.path.isfile(filename): abort(400) # get data in memory, up to 100M (limit set in nginx config) body = request.data body_len = len(body) # verify content-length matches provided if clen != body_len: abort(400) # hash data h = hashlib.new('sha256') h.update(body) # verify hash matches provided if h.hexdigest() != hexstr: abort(400) # write to filesystem try: outf = open(filename, 'wb') outf.write(body) outf.close() except OSError: abort(500) body = None # Create, expiration times tm_creat = int(time.time()) tm_expire = tm_creat + (24 * 60 * 60) # Add hash metadata to db # TODO: test for errors, unlink file if so cursor.execute(SQLS_HASH_INSERT, (hexstr, body_len, tm_creat, tm_expire, ctype, pkh)) return ("true\n", 200, { 'Content-length': body_len, 'Content-type': 'application/json', })
def test_check_identity(): data = b'hello world' out = b58decode_check(b58encode_check(data)) assert_that(out, equal_to(data))
def test_check_failure(): data = '3vQB7B6MrGQZaxCuFg4oH' with assert_raises(ValueError): b58decode_check(data)
def _wif2priv(wif): ad = base58.b58decode_check(wif) if str(wif, 'ascii')[0] == 'K' or str(wif, 'ascii')[0] == 'L': return ad[1:-1] else: return ad[1:]
def _decode_bitcoin_secret(address): secret_plain = b58decode_check(address) if not secret_plain.startswith(b'\x80') or len(secret_plain) != 33: raise ValueError('Invalid secret key. Uncompressed keys only.') return secret_plain[1:]