def init_rpc_co(self): try: if (self.rpc_addr): self.proxy = RawProxy(service_url=self.rpc_addr, service_port=self.rpc_port) else: self.proxy = RawProxy(service_port=self.rpc_port) except Exception as e: perror("Unable to connect: " + str(e))
def Mokestis(): p = RawProxy() #txidd = input("Iveskite transakcija") #txid = str(txidd) txid = '0627052b6f28912f2703066a912ea577f2ce4da4caa5a5fbd8a57286c345c2f2' raw_tx = p.getrawtransaction(txid) decoded_tx = p.decoderawtransaction(raw_tx) sumIn = 0 sumOut = 0 for output in decoded_tx['vin']: vinTxId = output['txid'] raw_vintx = p.getrawtransaction(vinTxId) decoded_vintx = p.decoderawtransaction(raw_vintx) vin_vout = output['vout'] for out in decoded_vintx['vout']: if (out['n'] == vin_vout): sumIn += out['value'] for output in decoded_tx['vout']: sumOut += output['value'] tx_fee = sumIn - sumOut print("Transakcijos: ", txid) print("mokestis: ", tx_fee, "BTC")
def send_rpc_cmd(self, rpc_cmd, *nodes): # print('Sending rpc command: {}'.format(' '.join(rpc_cmd))) proxies = {} for n in nodes: proxies[n] = RawProxy('http://{user}:{password}@{host}:{rpcport}'.format(**self.nodes[n])) # try convert rpc params from strings to ints for idx, val in enumerate(rpc_cmd): try: rpc_cmd[idx] = int(val) except ValueError: if val in {'False', 'false'}: rpc_cmd[idx] = False elif val in {'True', 'true'}: rpc_cmd[idx] = True for node in nodes: retry = 1 while True: try: cmd, *args = rpc_cmd # print("command:", rpc_cmd) output = getattr(proxies[int(node)], cmd)(*args) # print(output) return output except JSONRPCError as e: retry += 1 if e.error['code'] == -26: raise TxVerifyError('Error during tx validation: {}'.format(e.error['message'])) if e.error['code'] != -28 or retry > 3: raise SendCommandError("Error trying to send command to bitcoincli, " "error code: {}, message: {}".format(e.error['code'], e.error['message'])) sleep(3 * (retry*2))
def Patikra(): p = RawProxy() BHeight = 277316 BHash = p.getblockhash(BHeight) Block = p.getblock(BHash) BVer = Block['version'] BPrevHash = Block['previousblockhash'] BNonce = Block['nonce'] BTime = Block['time'] BMerkle = Block['merkleroot'] BBits = Block['bits'] BPrevHash = SwapOrder(BPrevHash) BMerkle = SwapOrder(BMerkle) BBits = SwapOrder(BBits) BNonce = Endian(BNonce) BTime = Endian(BTime) BVer = Endian(BVer) Hex = (BVer + BPrevHash + BMerkle + BTime + BBits + BNonce) HexBinary = codecs.decode(Hex, 'hex') Hash1 = hashlib.sha256(HexBinary).digest() Hash2 = hashlib.sha256(Hash1).digest() Hash3 = codecs.encode(Hash2[::-1], 'hex_codec') FinalHash = codecs.decode(Hash3) print("Block Hash", BHash) print("Verified Block Hash", FinalHash)
def get_utxo(index, txid): p = RawProxy() raw_tx = p.getrawtransaction(txid) decoded_tx = p.decoderawtransaction(raw_tx) outputs = decoded_tx['vout'] utxo = outputs[index] return utxo['value']
class FeeCalculator: __rawProxy = RawProxy() def calculate(self, trxId): trx = self.__getTransaction(trxId) inputSum = 0 outputSum = 0 for vOutput in trx['vout']: outputSum += vOutput['value'] for vInput in trx['vin']: inputSum += self.__getTrxOutputByIndex(vInput['txid'], vInput['vout']) return inputSum - outputSum def __getTrxOutputByIndex(self, trxId, outputIndex): trx = self.__getTransaction(trxId) itr = 0 for vOutput in trx['vout']: if outputIndex == itr: return vOutput['value'] itr = itr + 1 def __getTransaction(self, trxId): rawTrx = self.__rawProxy.getrawtransaction(trxId) return self.__rawProxy.decoderawtransaction(rawTrx)
class HashValidator: __rawProxy = RawProxy() def validate(self, blockHeight): blockHash = self.__rawProxy.getblockhash(int(blockHeight)) blockHeader = self.__rawProxy.getblockheader(blockHash) headerHex = (self.__toLittleEndian(blockHeader['versionHex']) + self.__toLittleEndian(blockHeader['previousblockhash']) + self.__toLittleEndian(blockHeader['merkleroot']) + self.__toLittleEndian(format(int(blockHeader['time']), 'x')) + self.__toLittleEndian(blockHeader['bits']) + self.__toLittleEndian(format(int(blockHeader['nonce']), 'x'))) headerBinary = binascii.unhexlify(headerHex) newHash = self.__toLittleEndian(hashlib.sha256(hashlib.sha256(headerBinary).digest()).hexdigest()) if blockHash == newHash: return True else: return False def __toLittleEndian(self, input): byteArr = bytearray.fromhex(input) byteArr.reverse() return ''.join(format(x, '02x') for x in byteArr)
def search_for_block_by_header(header): p = RawProxy() try: block_info = p.getblock(header) block_info['resulttype'] = 'block' return block_info except: return None
def get_txs(block_height): p = RawProxy() blockhash = p.getblockhash(block_height) block = p.getblock(blockhash) transactions = block['tx'] for txid in transactions: print txid
def search_for_transaction_by_txid(txid): p = RawProxy() try: transaction_info = p.getrawtransaction(txid, True) transaction_info['resulttype'] = 'transaction' return transaction_info except: return None
def search_for_block_by_height(height): p = RawProxy() try: int_height = int(height) block_hash = p.getblockhash(int_height) return search_for_block_by_header(block_hash) except: return None
def get_latest_blocks(): p = RawProxy() blocks_to_take = 10 if request.args.get('count'): blocks_to_take = int(blocks_to_take) blocks_count = p.getblockcount() block_heights = list(range(blocks_count - blocks_to_take, blocks_count)) block_hashes = list(map(p.getblockhash, block_heights)) block_hashes.reverse() # So latest hashes would go first return jsonify(block_hashes)
def get_blockhash(): p = RawProxy() print('Iveskite tikrinamo bloko numeri') height = input() try: blockhash = p.getblockhash(int(height)) return blockhash except Exception as e: logging.error(traceback.format_exc()) globals.control = 0 return
def get_blockchain_info(): p = RawProxy() # Run the getblockchaininfo command, store the resulting data in info blockchain_info = p.getblockchaininfo() filtered_info = { "chainType": blockchain_info["chain"], "blockCount": blockchain_info["blocks"], "validatedHeadersCount": blockchain_info["headers"], "difficulty": str(blockchain_info["difficulty"]), "verificationProgress": str(blockchain_info["verificationprogress"] * 100), "bestBlockHash": str(blockchain_info["bestblockhash"]) } return jsonify(filtered_info)
def check_block(): p = RawProxy() var = get_blockhash() if var is None: return header = p.getblockheader(var) header_hex = (to_little_endian(header['versionHex']) + to_little_endian(header['previousblockhash']) + to_little_endian(header['merkleroot']) + to_little_endian(format(int(header['time']), 'x')) + to_little_endian(header['bits']) + to_little_endian(format(int(header['nonce']), 'x'))) header_bin = binascii.unhexlify(header_hex) block_hask = hashlib.sha256( hashlib.sha256(header_bin).digest()).hexdigest() block_hask_le = to_little_endian(block_hask) if var == block_hask_le: print('Bloko hashas yra teisingas') else: print('Bloko hashas yra neteisingas') globals.control = 0
def find_transaction_fee(): p = RawProxy() print('Iveskite pasirinktos transakcijos id') txid = input_txid() txinval = 0 txoutval = 0 try: raw_tx = p.getrawtransaction(txid) except Exception as e: logging.error(traceback.format_exc()) globals.control = 0 return decoded_tx = p.decoderawtransaction(raw_tx) vins = decoded_tx['vin'] vouts = decoded_tx['vout'] for input in vins: txinval = txinval + get_utxo(input['vout'], input['txid']) for output in vouts: txoutval = txoutval + output['value'] globals.control = 0 print('Transakcijos kaina:') print(f'{txinval - txoutval} BTC') return
def Brangiausia(): p = RawProxy() txid = "4410c8d14ff9f87ceeed1d65cb58e7c7b2422b2d7529afc675208ce2ce09ed7d" raw_tx = p.getrawtransaction(txid) decoded_tx = p.decoderawtransaction(raw_tx) sumIn = 0 sumOut = 0 for output in decoded_tx['vin']: vinTxId = output['txid'] raw_vintx = p.getrawtransaction(vinTxId) decoded_vintx = p.decoderawtransaction(raw_vintx) vin_vout = output['vout'] for out in decoded_vintx['vout']: if (out['n'] == vin_vout): sumIn += out['value'] for output in decoded_tx['vout']: sumOut += output['value'] tx_fee = sumIn - sumOut print("Transakcijos: ", txid) print("mokestis: ", tx_fee, "BTC")
def checkBlock(): hexcoding = 'hex_codec' p = RawProxy() blockId = raw_input("Enter Block Id: ") blockhash = p.getblockhash(int(blockId)) block = p.getblock(blockhash) version = block['versionHex'] hashPrevBlock = block['previousblockhash'] hashMerkleRoot = block['merkleroot'] time = block['time'] bits = block['bits'] nonce = block['nonce'] nonce = hex(int(0x100000000) + int(nonce))[-8:] time = hex(int(0x100000000) + int(time))[-8:] version = (version.decode(hexcoding))[::-1].encode(hexcoding) hashPrevBlock = (hashPrevBlock.decode(hexcoding))[::-1].encode(hexcoding) hashMerkleRoot = (hashMerkleRoot.decode(hexcoding))[::-1].encode(hexcoding) time = (time.decode(hexcoding))[::-1].encode(hexcoding) bits = (bits.decode(hexcoding))[::-1].encode(hexcoding) nonce = (nonce.decode(hexcoding))[::-1].encode(hexcoding) header_hex = (version + hashPrevBlock + hashMerkleRoot + time + bits + nonce) header_bin = header_hex.decode('hex') hash = hashlib.sha256(hashlib.sha256(header_bin).digest()).digest() print("Calculated hash:") print(hash[::-1].encode(hexcoding)) print("First hash:") print(blockhash)
def checkTrans(): transValue = 0 transId = raw_input("Enter transaction Id: ") p = RawProxy() trans = p.decoderawtransaction(p.getrawtransaction(transId)) for outputTrans in trans['vin']: transIdLocal = outputTrans['txid'] vout = outputTrans['vout'] transLocal = p.decoderawtransaction(p.getrawtransaction(transIdLocal)) for outputTransLocal in transLocal['vout']: if outputTransLocal['n'] == vout: transValue = transValue + outputTransLocal['value'] for output in trans['vout']: transValue = transValue - output['value'] print(transValue)
#!/usr/bin/python3 from bitcoin.rpc import RawProxy from os.path import expanduser import os import sys rpc_interface = RawProxy( ) # Intitialize/Construct(?) the imported function to use the rpc interface def help(): print('Theese are the available commands:\n') print('help\t- this help function') print('create\t- create a new multi signature bitcoin address') print( 'spend\t- spend from a multi signature bitcoin address (not available yet)' ) print('exit\t- terminate the program\n') def account_exists(account_name): # Check if the account name is valid check_name = rpc_interface.getaddressesbyaccount( account_name) # Request addresses in the given account if not check_name: # If bitcoind returns an empty list print('This account name has not been used.') return False else: print('This account name exists in bitcoind.')
blockHeader = self.node.getblockheader(blockHash) headerHex = ( self.toLittleEndian(blockHeader['versionHex']) + self.toLittleEndian(blockHeader['previousblockhash']) + self.toLittleEndian(blockHeader['merkleroot']) + self.toLittleEndian(format(int(blockHeader['time']), 'x')) + self.toLittleEndian(blockHeader['bits']) + self.toLittleEndian(format(int(blockHeader['nonce']), 'x'))) headerBinary = binascii.unhexlify(headerHex) calculatedHash = self.toLittleEndian( hashlib.sha256(hashlib.sha256(headerBinary).digest()).hexdigest()) if blockHash == calculatedHash: return True else: return False def toLittleEndian(self, input): byteArr = bytearray.fromhex(input) byteArr.reverse() return ''.join(format(x, '02x') for x in byteArr) node = RawProxy() block = int(raw_input('Enter a block to validate -> ')) if HashValidator(node).validate(block): print('Block is valid') else: print('Block is invalid')
from tx import Tx, TxIn, TxOut from script import p2pkh_script, Script def createAddress(passphrase): secret = little_endian_to_int(hash256(passphrase)) publicKey = PrivateKey(secret).point address = publicKey.address(testnet=True) return address def is_unspent(txid, index, proxy): return proxy.gettxout(txid, index) == None p = RawProxy(service_port=18332) # Sender Information sender_secret = b'[email protected] Tranquility Cracks is a hidden gem that many seek but few find' secret = little_endian_to_int(hash256(sender_secret)) private_key = PrivateKey(secret) public_key = private_key.point sender_address = public_key.address(testnet=True) # Receiver Information receiver_address = createAddress(b'some salt for this receiver address') # What is in our wallet that we can spend? (this one has 0.01 tBTC) tx_in_id = 'acf22005638e60379aa43d4cd2a5eb47a0fa1fefc5883eecf83329a607431d50' tx_in_index = 1 tx_input = TxIn(bytes.fromhex(tx_in_id), tx_in_index)
#!/usr/bin/env python3 import codecs from bitcoin.rpc import RawProxy if __name__ == '__main__': conf = input('Please enter path to the configuration file: ') proxy = RawProxy(btc_conf_file=conf) numblocks = proxy.getblockcount() + 1 fp = codecs.open('out.csv', 'w', 'utf-8') for idx in range(numblocks): blockinfo = proxy.getblock(proxy.getblockhash(idx)) fp.write(','.join( map(str, [ blockinfo['height'], blockinfo['time'], blockinfo['difficulty'], ])) + '\n') fp.close() # End of File
def listen(): serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind(('localhost', 8331)) serversocket.listen(5) alldata = [] while True: (clientsocket, address) = serversocket.accept() res = '' while True: data = clientsocket.recv(1024).decode(encoding='UTF-8') if '*' in data: alldata.append(data[:data.find('*')]) res = ''.join(alldata) alldata = [data[data.find('*') + 1:]] break else: alldata.append(data) if 'NEWTX' in res: txid = res[res.find(':') + 1:] try: raw_tx = RawProxy( btc_conf_file=CONF_PATH).getrawtransaction(txid) tx = RawProxy( btc_conf_file=CONF_PATH).decoderawtransaction(raw_tx) for output in tx['vout']: for address in output['scriptPubKey']['addresses']: if address in Address.objects.all().values_list( 'btc', flat=True): Incoming_btc.objects.create( user=Address.objects.get(btc=address).user, address=address, btc=output['value'], confirmations=0, txid=txid) displayed_address = Address.objects.get( btc=address) displayed_address.btc = RawProxy( btc_conf_file=CONF_PATH).getnewaddress( '', 'bech32') displayed_address.save() except JSONRPCError: pass elif 'NEWBLOCK' in res: new_blockhash = res[res.find(':') + 1:] for txid in Incoming_btc.objects.all().values_list('txid', flat=True): for (blockhash, _) in zip(get_blockhash(new_blockhash), range(CHECK_CONFIRMATIONS)): try: RawProxy(btc_conf_file=CONF_PATH).getrawtransaction( txid, False, blockhash) confirmations = RawProxy( btc_conf_file=CONF_PATH).getblock( blockhash)['confirmations'] Incoming_btc.objects.filter(txid=txid).update( confirmations=confirmations) if confirmations >= TRESHOLD_CONFIRMATIONS: for record in Incoming_btc.objects.filter( txid=txid).values('user', 'address', 'btc'): Deposit_btc.objects.create( address=record['address'], btc=record['btc'], datetime=timezone.now(), user_id=record['user']) Balance.objects.filter( user=record['user']).update(btc=F('btc') + record['btc']) Incoming_btc.objects.filter(txid=txid).delete() break except JSONRPCError: pass
def get_blockhash(blockhash): while True: yield blockhash blockhash = RawProxy( btc_conf_file=CONF_PATH).getblock(blockhash)['previousblockhash']
def get_new_address(): return RawProxy(btc_conf_file=CONF_PATH).getnewaddress('', 'bech32')
def send(address, amount, fee_per_kB): RawProxy(btc_conf_file=CONF_PATH).settxfee(fee_per_kB) RawProxy(btc_conf_file=CONF_PATH).sendtoaddtess(address, amount)
# This simple wallet works with bitcoind and will only work with 2-of-3 multisigs # Using the python-bitcoinlib library # 如何分布三个私钥的存储 # 一个自己使用,一个存放在wallet provider, 一个放在最安全的地方,一般不用 # 如何来花这个multisig addr中的比特币? # 比如你想到taobao.com上去花比特币买东西,你这时用自己的私钥来 createrawTransaction,但是这时交易显示的花费是失败的, # 这时你将signed之后的原始交易发给第三方平台,这时你就让它用私钥来sign你sign过的transaction,这时会显示花费成功 import bitcoin from bitcoin.rpc import RawProxy bitcoin.SelectParams('testnet') p = RawProxy() #creates an object called p that allows for bitcoind calls money = p.getbalance() print(money) # YOU NEED AT LEAST TWO OF THE PRIVATE KEYS FROM PART ONE linked to your MULTI-SIG ADDRESS multisigprivkeyone = "cPw3fUfVnhZNNpg8mEnoNcbrk4VhhobDohZBcZdrS3pfP53ymhB2" multisigprivkeytwo = "cPpjLNPGgvwfCSUuXk1qExmBQB71piHxMUxmukzLr43m38VqsCHo" multisigprivkeythree = "cT2YurYhGWiShznfwzcsysf1a4koDhP369dtWiKBTyZV1HMTGLEk" ChangeAddress = "2NBwWtf4mQcmx1mR2tNSsuh21LsoPtbxA79" # Makes Sure to set your own personal Change Address SetTxFee = int(0.00005461 * 100000000) # ask your account, how much money you have unspent = p.listunspent( ) # Query wallet.dat file for unspent funds to see if we have multisigs to spend from print("Your Bitcoin-QT/d has", len(unspent), "unspent outputs") for i in range(0, len(unspent)):
from bitcoin.rpc import RawProxy from hashlib import sha256 import binascii import struct def hexify(value, type): return binascii.hexlify(struct.Struct(type).pack(value)) p = RawProxy() blockheight = 1337 blockhash = p.getblockhash(blockheight) block = p.getblock(blockhash) block_version = block['version'] previous_hash = block['previousblockhash'] hash_merkle_root = block['merkleroot'] bits = block['bits'] timestamp = block['time'] nonce = block['nonce'] header_hex = '{block_version}{previous_hash}{hash_merkle_root}{timestamp}{bits}{nonce}'.format( block_version=hexify(block_version, '<L'), previous_hash=binascii.hexlify(previous_hash.decode('hex')[::-1]), hash_merkle_root=binascii.hexlify(hash_merkle_root.decode('hex')[::-1]), timestamp=hexify(timestamp, '<L'), bits=binascii.hexlify(bits.decode('hex')[::-1]), nonce=hexify(nonce, '<L'))
def get_fee_per_kB(): return RawProxy(btc_conf_file=CONF_PATH).estimatesmartfee(5)['feerate']