def test_exercise_5(self): prev_tx_1 = bytes.fromhex( '11d05ce707c1120248370d1cbf5561d22c4f83aeba0436792c82e0bd57fe2a2f') prev_index_1 = 1 prev_tx_2 = bytes.fromhex( '51f61f77bd061b9a0da60d4bedaaf1b1fad0c11e65fdc744797ee22d20b03d15') prev_index_2 = 1 target_address = 'mwJn1YPMq7y5F8J3LkC5Hxg9PHyZ5K4cFv' target_amount = 0.0429 secret = 8675309 priv = PrivateKey(secret=secret) tx_ins = [] tx_ins.append(TxIn(prev_tx_1, prev_index_1, Script([]), 0xffffffff)) tx_ins.append(TxIn(prev_tx_2, prev_index_2, Script([]), 0xffffffff)) tx_outs = [] h160 = decode_base58(target_address) script_pubkey = p2pkh_script(h160) target_satoshis = int(target_amount * 100000000) tx_outs.append(TxOut(target_satoshis, script_pubkey)) tx_obj = Tx(1, tx_ins, tx_outs, 0, testnet=True) self.assertTrue(tx_obj.sign_input(0, priv)) self.assertTrue(tx_obj.sign_input(1, priv)) self.assertTrue(tx_obj.verify()) want = '01000000022f2afe57bde0822c793604baae834f2cd26155bf1c0d37480212c107e75cd011010000006a47304402204cc5fe11b2b025f8fc9f6073b5e3942883bbba266b71751068badeb8f11f0364022070178363f5dea4149581a4b9b9dbad91ec1fd990e3fa14f9de3ccb421fa5b269012103935581e52c354cd2f484fe8ed83af7a3097005b2f9c60bff71d35bd795f54b67ffffffff153db0202de27e7944c7fd651ec1d0fab1f1aaed4b0da60d9a1b06bd771ff651010000006b483045022100b7a938d4679aa7271f0d32d83b61a85eb0180cf1261d44feaad23dfd9799dafb02205ff2f366ddd9555f7146861a8298b7636be8b292090a224c5dc84268480d8be1012103935581e52c354cd2f484fe8ed83af7a3097005b2f9c60bff71d35bd795f54b67ffffffff01d0754100000000001976a914ad346f8eb57dee9a37981716e498120ae80e44f788ac00000000' self.assertEqual(tx_obj.serialize().hex(), want)
def __init__(self, serialized_psbt): self.role = "Finalizer" self.psbt = PSBT.parse(BytesIO(serialized_psbt)) for i in self.psbt.maps["inputs"]: if not self._check_for_sig(i): continue if IN_SIGHASH_TYPE not in i.keys(): continue if self._is_witness_input(i): if IN_WITNESS_SCRIPT not in i.keys(): continue # Step 3b: Then create scriptWitness new_scriptWitness = self._make_multisig_script(inp=i, witness=True) # Complete scriptWitness by adding the number of witness items to the beginning new_scriptWitness.insert(0, len(new_scriptWitness)) # Add key-type PSBT_IN_FINAL_SCRIPTWITNESS to PSBT with the finalized scriptWitness as its value i[IN_FINAL_SCRIPTWITNESS] = Script(new_scriptWitness).serialize() # Add key-type PSBT_IN_FINAL_SCRIPTSIG to PSBT with the finalized scriptSig as its value # For witness inputs, this is the redeemScript preceded by its length i[IN_FINAL_SCRIPTSIG] = encode_varint(len(i[IN_REDEEM_SCRIPT])) + i[IN_REDEEM_SCRIPT] elif IN_REDEEM_SCRIPT in i.keys(): # ASSUME MULTISIG i[IN_FINAL_SCRIPTSIG] = Script(self._make_multisig_script(i)).serialize() else: # ASSUME P2PKH found_sec = False for k in i.keys(): if k[:1] == IN_PARTIAL_SIG: # WTF IS THIS LOGIC??? if found_sec: continue sec = k[1:] sig = i[k] found_sec = True i[IN_FINAL_SCRIPTSIG] = Script([sig, sec]).serialize() self._clear_keyvalues(i)
def koopa_response(player: example.Wrap1, koopa: example.Wrap1, x, y): if koopa.getState() == 'hide': koopa.killScripts() if player.getState() == 'jump' and player.vy < 0: player.vy = 300 #koopa.move(-10 * x, 0, 0) left = 0 if (player.x < koopa.x) else 1 s = Script() s.add_action( act.SetState(state='walk2', entity_id=koopa.id, args={'left': left})) koopa.play(s) elif koopa.getState() == 'walk2': # hit player only if going towards player dx = player.x - koopa.x if (dx > 0 and not koopa.flipx) or (dx < 0 and koopa.flipx): player_hit_by_enemy(player) else: if player.getState() == "jump" and player.vy < 0: print('fokkami') player.vy = 300 s = Script() s.add_action(act.SetState(state='hide', entity_id=koopa.id)) s.add_action(act.Delay(20)) s.add_action( act.Blink(duration=2, blink_duration=0.2, entity_id=koopa.id)) s.add_action(act.SetState(state='walk', entity_id=koopa.id)) koopa.play(s) else: player_hit_by_enemy(player)
def hash_to_sign(self, input_index, sighash): '''Returns the integer representation of the hash that needs to get signed for index input_index''' # create a new transaction that's a clone of self # use self.__class__(self.version, self.tx_ins, self.tx_outs, self.locktime) alternate_tx = self.__class__(self.version, self.tx_ins, self.tx_outs, self.locktime) # iterate through inputs for tx_in in alternate_tx.tx_ins: # for each input, create new TxIn with blanked out script_sig # use Script(b'') tx_in.script_sig = Script(b'') # grab the input at input_index tx_in = alternate_tx.tx_ins[input_index] # replace input_index input with scriptPubKey from that input # use Script(tx_in.script_pubkey()) tx_in.script_sig = Script(tx_in.script_pubkey()) # grab the serialization serialization = alternate_tx.serialize() # add the sighash int in 4 bytes, little endian serialization += int_to_little_endian(sighash, 4) # get the double_sha256 of the tx serialization ds256 = double_sha256(serialization) # convert this to a big-endian integer using int.from_bytes(x, 'big') return int.from_bytes(ds256, 'big')
def test_example_6(self): tx_ins = [] prev_tx = bytes.fromhex( '0d6fe5213c0b3291f208cba8bfb59b7476dffacc4e5cb66f6eb20a080843a299') prev_index = 13 tx_ins.append(TxIn(prev_tx, prev_index, Script([]), 0xffffffff)) tx_outs = [] change_amount = int(0.33 * 100000000) change_h160 = decode_base58('mzx5YhAH9kNHtcN481u6WkjeHjYtVeKVh2') change_script = p2pkh_script(change_h160) tx_outs.append(TxOut(amount=change_amount, script_pubkey=change_script)) target_amount = int(0.1 * 100000000) target_h160 = decode_base58('mnrVtF8DWjMu839VW3rBfgYaAfKk8983Xf') target_script = p2pkh_script(target_h160) tx_outs.append(TxOut(amount=target_amount, script_pubkey=target_script)) transaction = Tx(1, tx_ins, tx_outs, 0, testnet=True) z = transaction.sig_hash(0) private_key = PrivateKey(secret=8675309) der = private_key.sign(z).der() sig = der + SIGHASH_ALL.to_bytes(1, 'big') sec = private_key.point.sec() transaction.tx_ins[0].script_sig = Script([sig, sec]) want = '010000000199a24308080ab26e6fb65c4eccfadf76749bb5bfa8cb08f291320b3c21e56f0d0d0000006b4830450221008ed46aa2cf12d6d81065bfabe903670165b538f65ee9a3385e6327d80c66d3b502203124f804410527497329ec4715e18558082d489b218677bd029e7fa306a72236012103935581e52c354cd2f484fe8ed83af7a3097005b2f9c60bff71d35bd795f54b67ffffffff02408af701000000001976a914d52ad7ca9b3d096a38e752c2018e6fbc40cdf26f88ac80969800000000001976a914507b27411ccf7f16f10297de6cef3f291623eddf88ac00000000' self.assertEqual(transaction.serialize().hex(), want)
def process_toggle_block_mention(self, minfo, keyword): log.debug(u'process_toggle_block_mention called with keyword: {}'.format(keyword.encode('utf8'))) user = session.query(Follower).filter_by(uniqueid = minfo['id']) try: user = user.one() except NoResultFound: user = session.query(Follower).filter_by(mention_id = minfo['screen_name']) try: user = user.one() except: user = Follower(minfo['screen_name'], minfo['name']) SCRIPT_STOP = u'알았다요. 이제 먼저 말 걸지 않겠다요.. ' SCRIPT_RESUME = u'헤헤 알았다요! 이제 닉시코가 먼저 말을 걸 수도 있다요!' if keyword.split()[1] in (u'중지', u'그만', u'중단'): # if suspend user.is_blocked = 1 log.info(u'사용자 블록 전환: '.format(minfo['screen_name'])) script = Script(SCRIPT_STOP) script.mention(minfo['screen_name']) self.do_tweet(script, minfo['id']) else: # if resume user.is_blocked = 0 log.info(u'사용자 블록 해제: '.format(minfo['screen_name'])) script = Script(SCRIPT_RESUME) script.mention(minfo['screen_name']) self.do_tweet(script, minfo['id']) session.add(user) session.commit() log.debug('toggle_block_mention done')
def test_example_1(self): z = 0x7c076ff316692a3d7eb3c3bb0f8b1488cf72e1afcd929e29307032997a838a3d sec = bytes.fromhex('04887387e452b8eacc4acfde10d9aaf7f6d9a0f975aabb10d006e4da568744d06c61de6d95231cd89026e286df3b6ae4a894a3378e393e93a0f45b666329a0ae34') sig = bytes.fromhex('3045022000eff69ef2b1bd93a66ed5219add4fb51e11a840f404876325a1e8ffe0529a2c022100c7207fee197d27c618aea621406f6bf5ef6fca38681d82b2f06fddbdce6feab601') script_pubkey = Script([sec, 0xac]) script_sig = Script([sig]) combined_script = script_sig + script_pubkey self.assertTrue(combined_script.evaluate(z))
def build_combo(fn, config, platform): print('building {0} {1} {2}...'.format(fn.__name__, config, platform)) bat = Script(True, fn.__name__, config, platform) #build script fn(bat) bat.run() print('installing {0} {1} {2}...'.format(fn.__name__, config, platform)) bat = Script(False, fn.__name__, config, platform) #istallation script fn(bat) bat.run()
def finalize_p2wpkh(self, sig, sec, redeem_script=None): '''Puts together the ScriptSig and Witness for a p2wpkh input so the input verifies.''' # if the RedeemScript is given, the ScriptSig is a single element Script of its raw serialization if redeem_script: self.script_sig = Script([redeem_script.raw_serialize()]) # else the ScriptSig should be empty else: self.script_sig = Script() # the Witness for p2wpkh is [sig, sec] self.witness = Witness([sig, sec])
def sig_hash(self, indice_input, tipo_hash): '''Devuelve la representación entera del hash que necesitas firmar para el índice indice_input''' # crea una nueva serie de tx_ins (alt_tx_ins) alt_tx_ins = [] # itera sobre self.tx_ins for tx_in in self.tx_ins: # crea un nuevo TxIn que tenga un script_sig (b'') en blanco y añáde a alt_tx_ins alt_tx_ins.append( TxIn( tx_previa=tx_in.tx_previa, indice_previo=tx_in.indice_previo, script_sig=Script([]), sequence=tx_in.sequence, )) # obtén el input en el indice_input input_firmante = alt_tx_ins[indice_input] # obtén el script_pubkey del input script_pubkey = input_firmante.script_pubkey(self.testnet) # el script_sig del input_firmante debería ser script_pubkey input_firmante.script_sig = script_pubkey # crea una transacción alternativa con las tx_ins modificadas alt_tx = self.__class__(versión=self.versión, tx_ins=alt_tx_ins, tx_outs=self.tx_outs, locktime=self.locktime) # añade el tipo_hash entero 4 bytes, little endian res = alt_tx.serializar() + int_a_little_endian(tipo_hash, 4) # obtén el doble_sha256 de la serialización de la tx s256 = doble_sha256(res) # convierte esto a un entero big-endian usando int.from_bytes(x, 'big') return int.from_bytes(s256, 'big')
def prueba_firmar_input(self): clave_privada = ClavePrivada(secreto=8675309) tx_ins = [] tx_previa = bytes.fromhex( '0025bc3c0fa8b7eb55b9437fdbd016870d18e0df0ace7bc9864efc38414147c8') tx_ins.append( TxIn( tx_previa=tx_previa, indice_previo=0, script_sig=Script([]), sequence=0xffffffff, )) tx_outs = [] h160 = decodificar_base58('mzx5YhAH9kNHtcN481u6WkjeHjYtVeKVh2') tx_outs.append( TxOut(cantidad=int(0.99 * 100000000), script_pubkey=script_p2pkh(h160))) h160 = decodificar_base58('mnrVtF8DWjMu839VW3rBfgYaAfKk8983Xf') tx_outs.append( TxOut(cantidad=int(0.1 * 100000000), script_pubkey=script_p2pkh(h160))) tx = Tx( versión=1, tx_ins=tx_ins, tx_outs=tx_outs, locktime=0, testnet=True, ) self.assertTrue(tx.firmar_input(0, clave_privada, SIGHASH_ALL))
def sign_input(self, idx, private_key, sighash_type=SIGHASH_ALL): '''Signs the input using the private key''' # get the signature hash (z) tx_in = self.tx_ins[idx] script_pubkey = tx_in.script_pubkey(testnet=self.testnet) if script_pubkey.is_p2wpkh_script(): z = self.sig_hash_bip143(idx) elif script_pubkey.is_p2pkh_script(): z = self.sig_hash(idx, sighash_type=sighash_type) #TODO p2sh-p2wpkh elif script_pubkey.is_p2wsh_script(): #z = self.sig_hash_bip143(idx, witness_script=tx_in.witness) raise NotImplementedError else: raise NotImplementedError # get der signature of z from private key der = private_key.sign(z).der() # append the sighash_type to der (use sighash_type.to_bytes(1, 'big')) sig = der + sighash_type.to_bytes(1, 'big') # calculate the sec sec = private_key.point.sec() # initialize a new script with [sig, sec] as the cmds script_sig = Script([sig, sec]) # change input's script_sig to new script if tx_in.segwit: self.tx_ins[idx].witness = script_sig else: self.tx_ins[idx].script_sig = script_sig # return whether sig is valid using self.verify_input if self.verify_input(idx): return script_sig else: return False
def sign_input(self, input_index, private_key): # get the signature hash (z) ## ## Might need to provide logic to get sig_hash depending on whether it is segwit or not. ## The following right now is for not segwit ## ## If spending a segwit utxo then --will need to look at the form of the utxo script pubkey ## z = self.sig_hash_bip143 ## else z = self.sig_hash(input_index) # get der signature of z from private key der = private_key.sign(z).der() # append the SIGHASH_ALL to der (use SIGHASH_ALL.to_bytes(1, 'big')) sig = der + SIGHASH_ALL.to_bytes(1, 'big') # calculate the sec sec = private_key.point.sec() # initialize a new script with [sig, sec] as the cmds script = Script([sig, sec]) print("Script_Sig from within sign_input: ", script) # change input's script_sig to new script self.tx_ins[input_index].script_sig = script # return whether sig is valid using self.verify_input # verify_input will return True if the signautre is valid verify = self.verify_input(input_index) print(verify) return verify
def new_commitment_tx(node, current_channel, cost, secret_hash): remote_peer = current_channel.peer # Create input using the output from the funding tx tx_in = TxIn(bytes.fromhex(current_channel.funding_tx.id()), 0) # Create 3 outputs. 1 to nodeA and 1 to nodeB and 1 to an HTLC script script_1 = p2pkh_script(decode_base58(node.address)) tx_out_1 = TxOut(amount=current_channel.local_amt - cost, script_pubkey=script_1) script_2 = p2pkh_script(decode_base58(remote_peer.btc_addr.decode())) tx_out_2 = TxOut(amount=current_channel.remote_amt, script_pubkey=script_2) #script_3 HTLC script_3 = Script([ 99, 168, secret_hash, 136, 118, 169, hash160(remote_peer.public_key.sec()), 103, encode_varint(1000), 177, 117, 118, 169, hash160(node.public_key.sec()), 104, 136, 172 ]) tx_out_3 = TxOut(amount=cost, script_pubkey=script_3) # Construct the commitment tx object commitment_tx = Tx(1, [tx_in], [tx_out_1, tx_out_2, tx_out_3], 0, True) #sign it commitment_tx.tx_ins[0].script_sig = get_script_sig( commitment_tx, node.private_key) return commitment_tx
def sig_hash(self, input_index, redeem_script=None): alt_tx_ins = [] for tx_in in self.tx_ins: alt_tx_ins.append( TxIn( prev_tx=tx_in.prev_tx, prev_index=tx_in.prev_index, script_sig=Script([]), sequence=tx_in.sequence, )) signing_input = alt_tx_ins[input_index] if redeem_script: print(redeem_script) signing_input.script_sig = redeem_script else: signing_input.script_sig = signing_input.script_pubkey( self.testnet) for i in alt_tx_ins: print(i.script_sig) alt_tx = self.__class__(version=self.version, tx_ins=alt_tx_ins, tx_outs=self.tx_outs, locktime=self.locktime) result = alt_tx.serialize() + int_to_little_endian(SIGHASH_ALL, 4) h256 = hash256(result) return int.from_bytes(h256, 'big')
def test_create_changer_from_pos(self): script_str = r''' func1( param1, param2, func32(adfd), func3(1,2,3,4, "abcdefg(fsdsd)"), func39(1,2,3,4, "abc'defg(fsdsd)"), [1, 2, 3, 4], func4(1,2,3,4, "abc'd\"ef'g(fsdsd)"), ")))))))", '((((((') func2(1,2,3)''' script = Script(script_str) manager = ParameterChangerManager(script) changer = manager._create_changer_from_pos(0) params = changer.get_parameters() self.assertEqual(params[0], 'param1') self.assertEqual(params[1], 'param2') self.assertEqual(params[2], 'func32(adfd)') self.assertEqual(params[3], 'func3(1,2,3,4,\n "abcdefg(fsdsd)")') self.assertEqual(params[4], 'func39(1,2,3,4,\n "abc\'defg(fsdsd)")') self.assertEqual(params[5], '[1, 2, 3, 4]') self.assertEqual(params[6], 'func4(1,2,3,4,\n "abc\'d\\"ef\'g(fsdsd)")') self.assertEqual(params[7], '")))))))"') self.assertEqual(params[8], '\'((((((\'')
def sign_input(self, input_index: int, private_key): z = self.sig_hash(input_index) der = private_key.sign(z).der() sig = der+SIGHASH_ALL.to_bytes(1, "big") sec = private_key.point.sec() self.tx_ins[input_index].script_sig = Script([sig, sec]) return self.verify_input(input_index)
def __init__(self): self.list_speaks = [] self.born_time = time.time() self.attributes = {} self.stop = False self.user = User() self.script = Script(self)
def build_transaction(transidsarr, transindexarr, pubeysarr, amountsarr, privatekey): tx_ins = buildinputs(transidsarr, transindexarr) tx_outs = buildoutputs(pubkeysarr, amountsarr) tx_obj = Tx(version=1, tx_ins=tx_ins, tx_outs=tx_outs, locktime=0, testnet=True) hash_type = SIGHASH_ALL z = tx_obj.sig_hash(0, hash_type) pk = PrivateKey(secret=privatekey) sighash = SIGHASH_ALL z = tx_obj.sig_hash(0, sighash) #print(z) sig = pk.sign(z) #print("r: " + str(sig.r)) #print("s: " + str(sig.s)) der = pk.sign(z).der() sig = der + bytes([sighash]) sec = pk.point.sec() tx_obj.tx_ins[0].script_sig = Script([sig, sec]) #print("serialized:") #print(hexlify(Script([sig,sec]).serialize())) #print("----------") return hexlify(tx_obj.serialize())
def sign_input_multisig_1by1(self, input_index, private_key,privkey_index, redeem_script,n): '''Signs the input using the private key n: n signatures that can sign transaction. private_key: must be a PrivateKey object. privkey_index: is the index of the private key according to the order of the public keys. ''' # get the signature hash (z) z = self.sig_hash(input_index, redeem_script) # get der signature of z from private key cmds = self.tx_ins[input_index].script_sig.cmds if len(cmds) == 0: #We create an array full of 0s with a lentgth of n+1. n is the number of possible private keys that can #sign the transaction. This way we can place the signatures in the right order. We get rid of the unnecesarry #0s later. print(f"cmds is empty. Creating new set of commands") cmds = [0]*(n) #we also need to append at the end the serialized redeem script: cmds.append(redeem_script.serialize()[1:]) der = private_key.sign(z).der() # append the SIGHASH_ALL to der (use SIGHASH_ALL.to_bytes(1, 'big')) sig = der + SIGHASH_ALL.to_bytes(1, 'big') #we add 1 to the index because of the OP_0 bug. cmds[privkey_index] = sig #commands.append(*redeem_script.cmds) print(f"sign_input_multisig commands: {cmds}") script_sig = Script(cmds) #script_sig = cmds # change input's script_sig to new script self.tx_ins[input_index].script_sig = script_sig # return whether sig is valid using self.verify_input #return self.verify_input(input_index) return True
def add_channel(local_node, remote_peer, input_tx_id, input_tx_index): tx_in = TxIn(bytes.fromhex(input_tx_id), input_tx_index) local_amount = tx_in.value() remote_amount = 0 # Construct the output: amount, scriptPubKey = 2-of-2 Bare Multisig = Script([op_1, pubkey1, pubkey2, op_2, op_checkmultisig]) scriptPubKey = Script([ 0x52, local_node.public_key.sec(), remote_peer.public_key.sec(), 0x52, 0xae ]) tx_out = TxOut(amount=local_amount, script_pubkey=scriptPubKey) # Construct the transaction object funding_tx = Tx(1, [tx_in], [tx_out], 0, True) # Sign the input funding_tx.sign_input(0, local_node.private_key) #send channel request new_channel = Channel(remote_peer, local_amount, remote_amount, funding_tx) remote_peer.send(str.encode(new_channel.toJSON())) return new_channel
def test_exercise_4(self): prev_tx = bytes.fromhex( '75a1c4bc671f55f626dda1074c7725991e6f68b8fcefcfca7b64405ca3b45f1c') prev_index = 1 target_address = 'miKegze5FQNCnGw6PKyqUbYUeBa4x2hFeM' target_amount = 0.01 change_address = 'mzx5YhAH9kNHtcN481u6WkjeHjYtVeKVh2' change_amount = 0.009 secret = 8675309 priv = PrivateKey(secret=secret) tx_ins = [] tx_ins.append(TxIn(prev_tx, prev_index, Script([]), 0xffffffff)) tx_outs = [] h160 = decode_base58(target_address) script_pubkey = p2pkh_script(h160) target_satoshis = int(target_amount * 100000000) tx_outs.append(TxOut(target_satoshis, script_pubkey)) h160 = decode_base58(change_address) script_pubkey = p2pkh_script(h160) change_satoshis = int(change_amount * 100000000) tx_outs.append(TxOut(change_satoshis, script_pubkey)) tx_obj = Tx(1, tx_ins, tx_outs, 0, testnet=True) self.assertTrue(tx_obj.sign_input(0, priv)) self.assertTrue(tx_obj.verify()) want = '01000000011c5fb4a35c40647bcacfeffcb8686f1e9925774c07a1dd26f6551f67bcc4a175010000006b483045022100a08ebb92422b3599a2d2fcdaa11f8f807a66ccf33e7f4a9ff0a3c51f1b1ec5dd02205ed21dfede5925362b8d9833e908646c54be7ac6664e31650159e8f69b6ca539012103935581e52c354cd2f484fe8ed83af7a3097005b2f9c60bff71d35bd795f54b67ffffffff0240420f00000000001976a9141ec51b3654c1f1d0f4929d11a1f702937eaf50c888ac9fbb0d00000000001976a914d52ad7ca9b3d096a38e752c2018e6fbc40cdf26f88ac00000000' self.assertEqual(tx_obj.serialize().hex(), want)
def test_sign_input(self): private_key = PrivateKey(secret=8675309) tx_ins = [] prev_tx = bytes.fromhex( '0025bc3c0fa8b7eb55b9437fdbd016870d18e0df0ace7bc9864efc38414147c8') tx_ins.append( TxIn( prev_tx=prev_tx, prev_index=0, script_sig=Script([]), sequence=0xffffffff, )) tx_outs = [] h160 = decode_base58('mzx5YhAH9kNHtcN481u6WkjeHjYtVeKVh2') tx_outs.append( TxOut(amount=int(0.99 * 100000000), script_pubkey=p2pkh_script(h160))) h160 = decode_base58('mnrVtF8DWjMu839VW3rBfgYaAfKk8983Xf') tx_outs.append( TxOut(amount=int(0.1 * 100000000), script_pubkey=p2pkh_script(h160))) tx = Tx( version=1, tx_ins=tx_ins, tx_outs=tx_outs, locktime=0, testnet=True, ) self.assertTrue(tx.sign_input(0, private_key, SIGHASH_ALL))
def clear(dir, start, end, mode): aS = Script(dir) if mode == "system": aS.s.nTask() else: aS.s.nScript() aS.s.allocm(1, 0, AnyType(16)) aS.s.clearm(0) now = int(time() * 1e9) iS = now + int(start * 1e9) iE = now + int(end * 1e9) aS.s.immevl(1, AnyType(iS)) aS.s.selfsc(1) aS.s.savevl(1, 0, AnyType(0)) aS.s.immevl(1, AnyType(iE)) aS.s.selfsc(1) aS.s.savevl(1, 0, AnyType(8)) scriptCap = UUID(aS.cfg.keys["capWorkersClearer"]['k']) if mode == "system": aS.s.callsy(0, scriptCap) else: aS.s.selfst(0, 1) aS.s.ret() aS.s.test() aS.s.push()
def test_example_1(self): tx_ins = [] prev_tx = bytes.fromhex( '8be2f69037de71e3bc856a6627ed3e222a7a2d0ce81daeeb54a3aea8db274149') prev_index = 4 tx_ins.append(TxIn(prev_tx, prev_index)) tx_outs = [] h160 = decode_base58('mzx5YhAH9kNHtcN481u6WkjeHjYtVeKVh2') tx_outs.append( TxOut( amount=int(0.38 * 100000000), script_pubkey=p2pkh_script(h160), )) h160 = decode_base58('mnrVtF8DWjMu839VW3rBfgYaAfKk8983Xf') tx_outs.append( TxOut( amount=int(0.1 * 100000000), script_pubkey=p2pkh_script(h160), )) tx_obj = Tx(1, tx_ins, tx_outs, 0, testnet=True) z = tx_obj.sig_hash(0) pk = PrivateKey(secret=8675309) der = pk.sign(z).der() sig = der + SIGHASH_ALL.to_bytes(1, 'big') sec = pk.point.sec() tx_obj.tx_ins[0].script_sig = Script([sig, sec]) want = '0100000001494127dba8aea354ebae1de80c2d7a2a223eed27666a85bce371de3790f6e28b040000006b483045022100fa3032607b50e8cb05bedc9d43f986f19dedc22e61320b9765061c5cd9c66946022072d514ef637988515bfa59a660596206de68f0ed4090d0a398e70f4d81370dfb012103935581e52c354cd2f484fe8ed83af7a3097005b2f9c60bff71d35bd795f54b67ffffffff0280d54302000000001976a914d52ad7ca9b3d096a38e752c2018e6fbc40cdf26f88ac80969800000000001976a914507b27411ccf7f16f10297de6cef3f291623eddf88ac00000000' self.assertEqual(tx_obj.serialize().hex(), want)
def init_variables(self): # Переменная времени self.clock = pygame.time.Clock() # Создание экземпляров классов self.menu = Menu(self.screen) self.script = Script(self.screen)
def sig_hash(self, input_index, hash_type): '''Returns the integer representation of the hash that needs to get signed for index input_index''' # create a new set of tx_ins (alt_tx_ins) alt_tx_ins = [] # iterate over self.tx_ins for tx_in in self.tx_ins: # create a new TxIn that has a blank script_sig (b'') and add to alt_tx_ins alt_tx_ins.append( TxIn( prev_tx=tx_in.prev_tx, prev_index=tx_in.prev_index, script_sig=Script([]), sequence=tx_in.sequence, )) # grab the input at the input_index signing_input = alt_tx_ins[input_index] # grab the script_pubkey of the input script_pubkey = signing_input.script_pubkey(self.testnet) # the script_sig of the signing_input should be script_pubkey signing_input.script_sig = script_pubkey # create an alternate transaction with the modified tx_ins alt_tx = self.__class__(version=self.version, tx_ins=alt_tx_ins, tx_outs=self.tx_outs, locktime=self.locktime) # add the hash_type int 4 bytes, little endian result = alt_tx.serialize() + int_to_little_endian(hash_type, 4) # get the double_sha256 of the tx serialization s256 = double_sha256(result) # convert this to a big-endian integer using int.from_bytes(x, 'big') return int.from_bytes(s256, 'big')
def parse_segwit(cls, s, version): '''Takes a byte stream and parses the segwit transaction in middle return a Tx object ''' marker = s.read(1) if marker != b'\x01': raise RuntimeError('Not a segwit transaction {}'.format(marker)) # num_inputs is a varint, use read_varint(s) num_inputs = read_varint(s) # each input needs parsing tx_ins = [] for _ in range(num_inputs): tx_ins.append(TxIn.parse(s)) # num_outputs is a varint, use read_varint(s) num_outputs = read_varint(s) # each output needs parsing tx_outs = [] for _ in range(num_outputs): tx_outs.append(TxOut.parse(s)) # now parse the witness program for tx_in in tx_ins: num_elements = read_varint(s) elements = [num_elements] for _ in range(num_elements): element_len = read_varint(s) elements.append(s.read(element_len)) tx_in.witness_program = Script(elements).serialize() # locktime is 4 bytes, little-endian locktime = little_endian_to_int(s.read(4)) # return an instance of the class (cls(...)) return cls(version, tx_ins, tx_outs, locktime)
def getScript(): ''' Store the JavaScript ''' scriptTags = ScriptTag().getScriptTag() for link in Links().getContent(): for scriptTag in scriptTags: headTag = scriptTag.replace('\n', '').split('|')[0] tailTag = scriptTag.replace('\n', '').split('|')[1] source = link.getPage() head = 0 length = len(source) flag = True while ((flag) and (head < length)): flag = False pos1 = source[head:].find(headTag) + head pos2 = source[head:].find(tailTag) + head if (pos1 >= head) and (pos2 >= head): flag = True tempString = source[pos1:pos2 + 9] tempString = tempString.replace('\t', '') tempString = tempString.replace('\n', '') tempString = tempString.replace(' ', '') script = Script(tempString, link.getUrl()) Scripts().addText(script) head = pos2 + 10 pass
def sig_hash(self, índice_input, tipo_hash): '''Devuelve la representación entera del hash que debe ser firmado para índice índice_input''' # crea una nueva serie de tx_ins (alt_tx_ins) alt_tx_ins = [] # itera sobre self.tx_ins for tx_in in self.tx_ins: # crea una nueva TxIn que tenga un script_sig en blanco (b'') y añádela a alt_tx_ins alt_tx_ins.append(TxIn( tx_previa=tx_in.tx_previa, índice_previo=tx_in.índice_previo, script_sig=Script([]), sequence=tx_in.sequence, )) # grab the input at the índice_input firmaring_input = alt_tx_ins[índice_input] # grab the script_pubkey of the input script_pubkey = firmaring_input.script_pubkey(self.testnet) # the script_sig of the firmaring_input should be script_pubkey firmaring_input.script_sig = script_pubkey # create an alternate transaction with the modified tx_ins alt_tx = self.__class__( versión=self.versión, tx_ins=alt_tx_ins, tx_outs=self.tx_outs, locktime=self.locktime) # añade el tipo_hash int 4 bytes, little endian res = alt_tx.serializar() + int_a_little_endian(tipo_hash, 4) # obtén el doble_sha256 de la serializacón de la tx s256 = doble_sha256(res) # convierte esto a big-endian entero usando int.from_bytes(x, 'big') return int.from_bytes(s256, 'big')