def __init__(self, tx): self.tx_hash = tx.hash().hex() inputs = [] for txin in tx.txs_in: inputs.append(TransactionUtils.getTxinPublicAddressByPre(txin)) self.tx_inputs = inputs outputs = [] for txout in tx.txs_out: if TransactionUtils.isCFTransationOut(txout): txout_type = '众筹交易' else: txout_type = '普通交易' outputs.append([ txout.address(), txout.coin_value, txout_type, TransactionUtils.getTransactionAndOutTime(txout), txout.usedState ]) self.tx_outputs = outputs self.time = time.ctime(TransactionUtils.getTransactionAndOutTime(tx)) self.total_coin = tx.total_in() self.fee = tx.fee() if TransactionUtils.isCFTransation(tx): self.tx_type = '众筹交易' self.lock_time = time.ctime(tx.cf_header.end_time) self.pre_hash = tx.cf_header.pre_hash.hex() else: self.tx_type = '普通交易' self.get_detail(tx)
def insert(blockchain): if BlockchainDao.isExist(blockchain): return if BlockchainDao.isPreBlockLinked(blockchain): #如果前一个区块被链接了 则失效 return for tx in blockchain.txs: TransactionUtils.updatePreOutState(tx) BlockchainDao.save(blockchain)
def set_details_out_txs(tx_outs): for tx_out in tx_outs: tx_hash = TransactionOutDao.searchParentTransactionHash(tx_out) tx = TransactionDao.searchByHash(tx_hash) in_addr = [] for tx_in in tx.txs_in: in_addr.append(TransactionUtils.getTxinPublicAddressByPre(tx_in)) tx_out.in_addr = in_addr if TransactionUtils.isCFTransationOut(tx_out): txout_type = '众筹交易' else: txout_type = '普通交易' tx_out.type = txout_type return tx_outs
def createNewBitcoinTx(publicAddrToValueArray): if len(publicAddrToValueArray) == 0: return None tx = TransactionUtils.createFirstTransaction(publicAddrToValueArray) if tx != None: SendMessage.broadcastTransactionMsg(tx) return tx
def __init__(self, cfs): self.cfs = cfs if len(cfs) == 0: return src_cf = cfs[0] des_cf = cfs[-1] self.cf_id = src_cf.hash().hex() self.target_amount = src_cf.cf_header.target_amount self.start_time = time.ctime( TransactionUtils.getTransactionAndOutTime(src_cf)) self.pubkey = src_cf.cf_header.pubkey self.end_time = time.ctime(src_cf.cf_header.end_time) self.lack_amount = des_cf.cf_header.lack_amount self.progress_rate = '%.2f %%' % ( (des_cf.cf_header.target_amount - des_cf.cf_header.lack_amount) / des_cf.cf_header.target_amount * 100) if src_cf.cf_header.cert not in ('', None): cert_obj = SecretKeyUtils.stringToCert(src_cf.cf_header.cert) self.cert = Cert(cert_obj) else: self.cert = None '''众筹成功,众筹失败''' if des_cf.cf_header.lack_amount <= 0: self.status = '众筹成功' elif src_cf.cf_header.end_time > int(time.time()): self.status = '正在进行' else: self.status = '众筹失败'
def total_out(self): total = sum(tx_out.coin_value for tx_out in self.txs_out) if TransactionUtils.isCFTransation(self): if self.cf_header.lack_amount <= 0: pre_tx = TransactionDao.searchByHash(self.cf_header.pre_hash) total = total - self.txs_out[0].coin_value + pre_tx.cf_header.lack_amount - self.cf_header.lack_amount return total
def stream(self, f, blank_solutions=False, include_unspents=False, include_witness_data=True): """Stream a Bitcoin transaction Tx to the file-like object f.""" include_witnesses = include_witness_data and self.has_witness_data() #### if TransactionUtils.isCFTransation(self): stream_struct("L", f, 2) stream_struct("#", f, self.cf_header.original_hash) stream_struct("Q", f, self.cf_header.target_amount) stream_struct("S", f, self.cf_header.pubkey.encode(encoding="utf-8")) stream_struct("L", f, self.cf_header.end_time) stream_struct("#", f, self.cf_header.pre_hash) stream_struct("Q", f, self.cf_header.lack_amount) else: stream_struct("L", f, 1) #### stream_struct("L", f, self.version) if include_witnesses: f.write(b'\0\1') stream_struct("I", f, len(self.txs_in)) for t in self.txs_in: t.stream(f, blank_solutions=blank_solutions) stream_struct("I", f, len(self.txs_out)) for t in self.txs_out: t.stream(f) if include_witnesses: for tx_in in self.txs_in: witness = tx_in.witness stream_struct("I", f, len(witness)) for w in witness: stream_bc_string(f, w) stream_struct("L", f, self.lock_time) if include_unspents and not self.missing_unspents(): self.stream_unspents(f)
def get_detail(self, tx): self.size = len(tx.as_hex()) #bytes block = TransactionUtils.searchParentBlock(tx) if block != None: self.block_hash = block.hash() else: self.block_hash = 'None' self.in_amount = tx.total_in() self.fee_per_byte = float(self.fee / self.size) * 10**8 rand = random.randint(13) in_scripts = [ '304402200f851e44a303c01203a9efce71b8472a53a69b0866795a613e8a18511fb7f9ad022054dc6a354462bf29d1128e064c30fb269ead454f59fbdc4c1a24736748cc9aed0102213c8e5d43845c0708fea710b0e6428b469bb4ac375ad278a408d8ee8f6657cf', '3045022100cd775627ea6ade0afcd7f2c621364686ce9e042a272b52dcddb110a742c4935102207046f05acec413c7cb31865e3411b926526c6231a4f29fb81b2c1c6f60738e5f010238e4a226145abe843ab470b3de2a1817020d8904b8040e85147e565c749fd2f7', '30440220314ad635a036190c7a62bae7b847c1ff3a9c0b0667ec1b887a256de412c4c706022061fccece187c4ab0ab80361e831189f225f4734c43ea171c41ce483f5316f1220103311914b86112e25397a2497b9df45c40646bf2bc480bfd1fb7b4ef896426eeed', '3045022100a41e45f2ef79bd3c85856d1ceec66d5a9c4255cca11fff4ae6ed2190230a527a02207a166a12211b5923facd8074b247a95c75ff7c78bcbd0200b6d681017d739d4e010330304ee875117e0a05b1e3930bc59b258c81cba236c0211cb55bee199270dc8a', '304402203324f7e5cd7755659385dfccfecb58a5c1ea9e4010820c7988e507b9b550e0a30220432ff43e1bf14137fa6963ee7585f7bdb294c2e27abb1386c2f59ec70df957000103fda0bce81384163131ac2f998d54039786f13d2638cc373b90926f0b5b8be729', '3045022100c9a884fec8fc25466c909601669fddc962c677069edd29af2a6814c399e106c20220579c80222bf754fd9b0886d1c1526070270166bb331492e66200bddf990b48b00103953a097c80665ca0d4721f7849d93b023c83afa793b705cf1015d77f94f952c4', '304402206d5d8ffbbc77541a7240485c948b024ec933bd822593979c41ca1c9259ba8acf02203ce5e63ed3753219510263ad0a95119a579c23aaf8ed9e47cd91b82f66e4b1b7010244f0e6eb11d9847fc0806b21606ce134dd049c821bc93bc3759c1102e745bca6', '30440220584fbdaa9ebbc64602b82977cacfe6a7da6a732a1c1c5b3003c3114f564babcc02201f8b81d15522d4faacf74da423516d624def15ee7dbb009b0589912491fc306601034629a351f6f513ba4234ea33e6791e3debc062902e6d8e03317da15915fdc480', '3045022100a009f847590f6d075d8342f82388cbd53c360a7b39306f2550c2afbaca1484e802205f61a41351df6e5314d3c1c4783aebae1dd4cbd3110c4a1b8a3316548441f2a101028c053c34abd8a1eb1b81989f75443a63188e19f4817ab2d461e6f9ea5f6e833c', '3045022100ce236387d8f4649be174c2b8e9f6e7a1e8032d2f29a0e95019f2f3202d5d6ec002207367219e5741fc19e95e05b4ec2c6b0fc64bab39025482f1975e464867e5b7bb01027461abd36ded728717cd42131f4b67a2e5e4603bb49b3b85fe2aab4cf8ea33eb', '30450221008a4c926bc0656c10fd09724a7f6198db32125182a6d8f2a72a6b6a215789c3a8022019b615f1eae9ba6303ac07fb0ed60e7450e0a11976a8d5bd7f66417e7a51528c01031f9bf0f18b3435dfd72734547ccb07d56adbb89e8b0202fb832a5f99386970b3', '3044022054562f435edb7286e563c7323e140125c9b99d92f0ed1cf644923f45891e5f1d02206a858c828710f9905a7ae085a955d9c2074f521354672662c251e891c02d492d0103b947c83d61cb6e25da0b3564cf85377b803fb80c0ca86d99d429bb7ad2d2aa87', '3045022100ae1eb6de01c7c51fc098fa03f4c229628452a06be52a6d7e1077898f4dfaa26902206443c3e98d7c0c46432f9ce993a9977436ee948cf4f070ea42fbbbb8270924af0103d4bbe6bbf74befb298a6629ac48f363524afb5773ea556d323cbf665032824aa' ] self.in_scripts = [] #这里怎么存看你方便 for i in range(len(self.tx_inputs)): self.in_scripts.append(in_scripts[random.randint(13)]) self.out_scripts = [] for txout in tx.txs_out: self.out_scripts.append(txout.script)
def createNewCFBitCoinTx(target_amount, pubkey_addr, end_time, pre_out_ids_for_fee=[]): return TransactionUtils.createFirstCFTransaction( target_amount, pubkey_addr, end_time, pre_out_ids_for_fee, '''-----BEGIN CERTIFICATE----- MIIDLjCCAhagAwIBAgIJAKTZkez5jH1vMA0GCSqGSIb3DQEBBQUAMG8xCzAJBgNV BAYTAkNOMRAwDgYDVQQIDAdCZWlqaW5nMQ0wCwYDVQQKDARUUFVCMREwDwYDVQQL DAhTZWN1cml0eTENMAsGA1UEAwwEdHB1YjEdMBsGCSqGSIb3DQEJARYOYWRtaW5A dHB1Yi5jb20wHhcNMTcwNTA4MDgxMTEwWhcNMjcwNTA2MDgxMTEwWjBvMQswCQYD VQQGEwJDTjEQMA4GA1UECAwHQmVpamluZzENMAsGA1UECgwEVFBVQjERMA8GA1UE CwwIU2VjdXJpdHkxDTALBgNVBAMMBHRwdWIxHTAbBgkqhkiG9w0BCQEWDmFkbWlu QHRwdWIuY29tMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEfStTpZiZKqNHJd2tYj/E MOGYOxFrh/TTliVA3lXadzablXdB27YqBAQirbGnw+NJuvgxa7CBi/nMqahAMTnC IGFBC/MLll7T4kS/f359/BiRbs4wMiuWNIzhoRugOAmgo3sweTAJBgNVHRMEAjAA MCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAd BgNVHQ4EFgQUZ/QPXuhN9WaAjgAOUhOVNN1cELcwHwYDVR0jBBgwFoAUNUt6r4IA A3nI7bjzFAXN2SRaapQwDQYJKoZIhvcNAQEFBQADggEBAMlXmy0e8a+KqUKZGW6P +arugviHapt0QLUAxdFPPwbAQm7/wJYcbguAwPvxUQlHMsdvdSqEdDQeOYiOwft8 IGZ0dzNbynvhyH99tK42p5wgWRQyf4hMHrOnCdCgYUNOUVB0kPsSZ1R1ajSgfE/0 Xsi5Jbhpqpzm2G8NVqnPXeYfzQPZwzSgDs9INLs4Yw6aA8ei1IT8ESPSUtCSbFiT HDB9G7UT/ZJBG6ZeGGONsf6ZOHZz38OkonBfL/tGS6NQzTFpr4H6yKyA3GlnYLOn E+FOPdz0PSfhJOsKHY+AXFWPVrKfOimfznDYHpyQ0G6X9s31MAjF1JddRG6Xo1Vl Ftg= -----END CERTIFICATE----- ''')
def createNormalBitCoinTx(pre_out_ids, publicAddrToValueArray): if len(pre_out_ids) == 0 or len(publicAddrToValueArray) == 0: return None tx = TransactionUtils.createTransaction(pre_out_ids, publicAddrToValueArray) if tx != None: SendMessage.broadcastTransactionMsg(tx) return tx
def createNormalCFBitCoinTx(pre_out_ids, pre_cf_hash, spendValue, otherPublicAddrToValueArray, refund_addr): if len(pre_out_ids) == 0: return None cf = TransactionUtils.createNormalCFTransaction( pre_out_ids, pre_cf_hash, spendValue, otherPublicAddrToValueArray, refund_addr) if cf != None: SendMessage.broadcastTransactionMsg(cf) return cf
def createNewCFBitCoinTx(target_amount, pubkey_addr, end_time, pre_out_ids_for_fee=[]): cf = TransactionUtils.createFirstCFTransaction(target_amount, pubkey_addr, end_time, pre_out_ids_for_fee) if cf != None: SendMessage.broadcastTransactionMsg(cf) return cf
def update(tx): if TransactionUtils.isCFTransation(tx): CoinSqlite3().exec_sql('Update TransactionInfo set `version`=?,`lock_time`=?,`parentBlockId`=?,`state`=?, `type` = ? ,original_hash = ?, target_amount = ?, pubkey = ?, end_time = ?, pre_hash = ?, lack_amount = ? , cert = ? where hash = ?', tx.version, tx.lock_time, tx.getBlockHash(), tx.state, 2, tx.cf_header.original_hash, tx.cf_header.target_amount, tx.cf_header.pubkey, tx.cf_header.end_time, tx.cf_header.pre_hash, tx.cf_header.lack_amount, tx.cf_header.cert, tx.hash()) else: CoinSqlite3().exec_sql('Update TransactionInfo set `version`=?,`lock_time`=?,`parentBlockId`=?, `state`=?, `type` = ? where hash = ?', tx.version, tx.lock_time, tx.getBlockHash(), tx.state, 1, tx.hash()) for index, txIn in enumerate(tx.txs_in): TransactionInDao.save(txIn, tx, index) for index, txOut in enumerate(tx.txs_out): TransactionOutDao.save(txOut, tx, index)
def insert(tx): if TransactionUtils.isCFTransation(tx): CoinSqlite3().exec_sql('INSERT INTO TransactionInfo(hash, version,lock_time,parentBlockId,state,type,original_hash, target_amount, pubkey, end_time, pre_hash, lack_amount, cert) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)', tx.hash(), tx.version, tx.lock_time, tx.getBlockHash(), tx.state, 2, tx.cf_header.original_hash, tx.cf_header.target_amount, tx.cf_header.pubkey, tx.cf_header.end_time, tx.cf_header.pre_hash, tx.cf_header.lack_amount, tx.cf_header.cert) else: CoinSqlite3().exec_sql('INSERT INTO TransactionInfo(hash, version,lock_time,parentBlockId,state,type) VALUES (?,?,?,?,?,?)', tx.hash(), tx.version, tx.lock_time, tx.getBlockHash(), tx.state, 1) for index, txIn in enumerate(tx.txs_in): TransactionInDao.save(txIn, tx, index) for index, txOut in enumerate(tx.txs_out): TransactionOutDao.save(txOut, tx, index)
def save(txOut, tx, index): deleteOld(tx, index) pubicAddress = txOut.address() end_time = 0 if TransactionUtils.isCFTransation(tx): if 0 == index: end_time = tx.cf_header.end_time CoinSqlite3().exec_sql( 'INSERT INTO TransactionInfoOut(coin_value, script, parentBlockId, parentTxId, state, `index`, pubicAddress, isToMe, usedState, end_time, isMyTx) VALUES (?,?,?,?,?,?,?,?,?,?,?)', txOut.coin_value, txOut.script, tx.getBlockHash(), tx.hash(), txOut.state, index, pubicAddress, SecretKeyDao.isMypubicAddress(pubicAddress), 0, end_time, SecretKeyDao.isMypubicAddress(txOut.address()))
def get_details(self): src_cf = self.cfs[0] des_cf = self.cfs[-1] tmpPreCF = src_cf promoter = [] for cf in self.cfs[1:]: promoter.append([ cf.hash().hex(), time.ctime(TransactionUtils.getTransactionAndOutTime(cf)), cf.txs_out[0].address(), tmpPreCF.cf_header.lack_amount - cf.cf_header.lack_amount ]) tmpPreCF = cf self.promoter = promoter self.process_date = [['day1', 20], ['day2', 30]]
def verify(blockchain): for tx in blockchain.txs: if not TransactionUtils.verify(tx): return False return True
def createNormalCFBitCoinTx(pre_out_ids, pre_cf_hash, spendValue, otherPublicAddrToValueArray, refund_addr): return TransactionUtils.createNormalCFTransaction( pre_out_ids, pre_cf_hash, spendValue, otherPublicAddrToValueArray, refund_addr)
def normal_tc_number(self): normal_tc = 0 for tx in self.txs: if not TransactionUtils.isCFTransation(tx): ++normal_tc return normal_tc
def cf_tc_number(self): cf_tc = 0 for tx in self.txs: if TransactionUtils.isCFTransation(tx): ++cf_tc return cf_tc
def dump_tx(tx, netcode, verbose_signature, disassembly_level, do_trace, use_pdb): address_prefix = address_prefix_for_netcode(netcode) tx_bin = stream_to_bytes(tx.stream) # print("Tx_type:%2d" % tx.tx_type) if TransactionUtils.isCFTransation(tx): print("original_hash : %s" % tx.cf_header.original_hash) print("target_amount : %s" % tx.cf_header.target_amount) print("pubkey : %s" % tx.cf_header.pubkey) print("end_time : %s" % tx.cf_header.end_time) print("pre_hash : %s" % tx.cf_header.pre_hash) print("lack_amount : %s" % tx.cf_header.lack_amount) print("Version: %2d tx hash %s %d bytes " % (tx.version, tx.id(), len(tx_bin))) print("TransactionIn count: %d; TransactionOut count: %d" % (len(tx.txs_in), len(tx.txs_out))) if tx.lock_time == 0: meaning = "valid anytime" elif tx.lock_time < LOCKTIME_THRESHOLD: meaning = "valid after block index %d" % tx.lock_time else: when = datetime.datetime.utcfromtimestamp(tx.lock_time) meaning = "valid on or after %s utc" % when.isoformat() print("Lock time: %d (%s)" % (tx.lock_time, meaning)) print("Input%s:" % ('s' if len(tx.txs_in) != 1 else '')) missing_unspents = tx.missing_unspents() def trace_script(old_pc, opcode, data, stack, altstack, if_condition_stack, is_signature): from pycoin.tx.script.tools import disassemble_for_opcode_data print("%3d : %02x %s" % (old_pc, opcode, disassemble_for_opcode_data(opcode, data))) if use_pdb: import pdb from pycoin.serialize import b2h print("stack: [%s]" % ', '.join(b2h(s) for s in stack)) if len(altstack) > 0: print("altstack: %s" % altstack) if len(if_condition_stack) > 0: print("condition stack: %s" % ', '.join(int(s) for s in if_condition_stack)) pdb.set_trace() traceback_f = trace_script if do_trace or use_pdb else None for idx, tx_in in enumerate(tx.txs_in): if disassembly_level > 0: def signature_for_hash_type_f(hash_type, script): return tx.signature_hash(script, idx, hash_type) if tx.is_coinbase(): print("%4d: COINBASE %12.5f mBTC" % (idx, satoshi_to_mbtc(tx.total_in()))) else: suffix = "" if tx.missing_unspent(idx): tx_out = None address = tx_in.bitcoin_address(address_prefix=address_prefix) else: tx_out = tx.unspents[idx] sig_result = " sig ok" if tx.is_signature_ok( idx, traceback_f=traceback_f) else " BAD SIG" suffix = " %12.5f mBTC %s" % (satoshi_to_mbtc( tx_out.coin_value), sig_result) address = tx_out.bitcoin_address(netcode=netcode) t = "%4d: %34s from %s:%-4d%s" % (idx, address, b2h_rev(tx_in.previous_hash), tx_in.previous_index, suffix) print(t.rstrip()) if disassembly_level > 0: out_script = b'' if tx_out: out_script = tx_out.script for (pre_annotations, pc, opcode, instruction, post_annotations) in \ disassemble_scripts( tx_in.script, out_script, tx.lock_time, signature_for_hash_type_f): for l in pre_annotations: print(" %s" % l) print(" %4x: %02x %s" % (pc, opcode, instruction)) for l in post_annotations: print(" %s" % l) if verbose_signature: signatures = [] for opcode in opcode_list(tx_in.script): if not opcode.startswith("OP_"): try: signatures.append(parse_signature_blob( h2b(opcode))) except UnexpectedDER: pass if signatures: sig_types_identical = (zip(*signatures)[1]).count( signatures[0][1]) == len(signatures) i = 1 if len(signatures) > 1 else '' for sig_pair, sig_type in signatures: print(" r{0}: {1:#x}\n s{0}: {2:#x}".format( i, *sig_pair)) if not sig_types_identical and tx_out: print(" z{}: {:#x} {}".format( i, tx.signature_hash(tx_out.script, idx, sig_type), sighash_type_to_string(sig_type))) if i: i += 1 if sig_types_identical and tx_out: print(" z:{} {:#x} {}".format( ' ' if i else '', tx.signature_hash(tx_out.script, idx, sig_type), sighash_type_to_string(sig_type))) print("Output%s:" % ('s' if len(tx.txs_out) != 1 else '')) for idx, tx_out in enumerate(tx.txs_out): amount_mbtc = satoshi_to_mbtc(tx_out.coin_value) address = tx_out.bitcoin_address(netcode=netcode) or "(unknown)" print("%4d: %34s receives %12.5f mBTC" % (idx, address, amount_mbtc)) if disassembly_level > 0: for (pre_annotations, pc, opcode, instruction, post_annotations) in \ disassemble_scripts(b'', tx_out.script, tx.lock_time, signature_for_hash_type_f): for l in pre_annotations: print(" %s" % l) print(" %4x: %02x %s" % (pc, opcode, instruction)) for l in post_annotations: print(" %s" % l) if not missing_unspents: print("Total input %12.5f mBTC" % satoshi_to_mbtc(tx.total_in())) print("Total output %12.5f mBTC" % satoshi_to_mbtc(tx.total_out())) if not missing_unspents: print("Total fees %12.5f mBTC" % satoshi_to_mbtc(tx.fee()))
def createNormalBitCoinTx(pre_out_ids, publicAddrToValueArray): return TransactionUtils.createTransaction(pre_out_ids, publicAddrToValueArray)
def get_my_unused_in_txs(): tx_ins = TransactionInDao.searchMyUnUsedTxIns() for tx_in in tx_ins: tx_in.addr = TransactionUtils.getTxinPublicAddressByPre(tx_in) return tx_ins
def createNewBitcoinTx(publicAddrToValueArray): return TransactionUtils.createFirstTransaction(publicAddrToValueArray)