def ScriptHash(self): if self._scriptHash is None: try: self._scriptHash = Crypto.ToScriptHash(self.Script) except binascii.Error: self._scriptHash = Crypto.ToScriptHash(self.Script, unhex=False) except Exception as e: logger.error("Could not create script hash: %s " % e) return self._scriptHash
def ImportMultiSigContractAddr(wallet, args): if len(args) < 4: print( "please specify multisig contract like such: 'import multisig_addr {pubkey in wallet} {minimum # of signatures required} {signing pubkey 1} {signing pubkey 2}...'" ) return if wallet is None: print("please open a wallet") return pubkey = get_arg(args, 0) m = get_arg(args, 1) publicKeys = args[2:] print( "1011010101 -https://github.com/SharedMocha/neo-python/edit/master/neo/Prompt/Commands/LoadSmartContract.py" ) if publicKeys[1]: print( "2022222222 -https://github.com/SharedMocha/neo-python/edit/master/neo/Prompt/Commands/LoadSmartContract.py" ) pubkey_script_hash = Crypto.ToScriptHash(pubkey, unhex=True) verification_contract = Contract.CreateMultiSigContract( pubkey_script_hash, int(m), publicKeys) address = verification_contract.Address wallet.AddContract(verification_contract) print("Added multi-sig contract address %s to wallet" % address) return address return 'Hello'
def __init__(self, public_key): pubkey_points = bitcoin.decode_pubkey(binascii.unhexlify(public_key), 'bin') pubx = pubkey_points[0] puby = pubkey_points[1] edcsa = ECDSA.secp256r1() self.PublicKey = edcsa.Curve.point(pubx, puby) self.PublicKeyHash = Crypto.ToScriptHash(self.PublicKey.encode_point(True), unhex=True)
def IsWalletTransaction(self, tx): """ Verifies if a transaction belongs to the wallet. Args: tx (TransactionOutput):an instance of type neo.Core.TX.Transaction.TransactionOutput to verify. Returns: bool: True, if transaction belongs to wallet. False, if not. """ for key, contract in self._contracts.items(): for output in tx.outputs: if output.ScriptHash.ToBytes() == contract.ScriptHash.ToBytes(): return True for script in tx.scripts: if script.VerificationScript: if bytes(contract.Script) == script.VerificationScript: return True for watch_script_hash in self._watch_only: for output in tx.outputs: if output.ScriptHash == watch_script_hash: return True for script in tx.scripts: if Crypto.ToScriptHash(script.VerificationScript, unhex=False) == watch_script_hash: return True return False
def ImportMultiSigContractAddr(wallet, args): if len(args) < 4: print( "please specify multisig contract like such: 'import multisig_addr {pubkey in wallet} {minimum # of signatures required} {signing pubkey 1} {signing pubkey 2}...'" ) return if wallet is None: print("please open a wallet") return pubkey = get_arg(args, 0) m = get_arg(args, 1) publicKeys = args[2:] if publicKeys[1]: pubkey_script_hash = Crypto.ToScriptHash(pubkey, unhex=True) verification_contract = Contract.CreateMultiSigContract( pubkey_script_hash, int(m), publicKeys) address = verification_contract.Address wallet.AddContract(verification_contract) print("Added multi-sig contract address %s to wallet" % address) return address return 'Hello'
def VerifyScripts(verifiable): """ Verify the scripts of the provided `verifiable` object. Args: verifiable (neo.IO.Mixins.VerifiableMixin): Returns: bool: True if verification is successful. False otherwise. """ try: hashes = verifiable.GetScriptHashesForVerifying() except Exception as e: logger.debug("couldn't get script hashes %s " % e) return False if len(hashes) != len(verifiable.Scripts): return False blockchain = GetBlockchain() for i in range(0, len(hashes)): verification = verifiable.Scripts[i].VerificationScript if len(verification) == 0: sb = ScriptBuilder() sb.EmitAppCall(hashes[i].Data) verification = sb.ms.getvalue() else: verification_hash = Crypto.ToScriptHash(verification, unhex=False) if hashes[i] != verification_hash: return False state_reader = GetStateReader() script_table = CachedScriptTable( DBCollection(blockchain._db, DBPrefix.ST_Contract, ContractState)) engine = ApplicationEngine(TriggerType.Verification, verifiable, script_table, state_reader, Fixed8.Zero()) engine.LoadScript(verification) invocation = verifiable.Scripts[i].InvocationScript engine.LoadScript(invocation) try: success = engine.Execute() state_reader.ExecutionCompleted(engine, success) except Exception as e: state_reader.ExecutionCompleted(engine, False, e) if engine.ResultStack.Count != 1 or not engine.ResultStack.Pop( ).GetBoolean(): Helper.EmitServiceEvents(state_reader) return False Helper.EmitServiceEvents(state_reader) return True
def ScriptHash(self): if self._scriptHash is None: self._scriptHash = Crypto.ToScriptHash(self.Script) return self._scriptHash
def GenesisBlock() -> Block: """ Create the GenesisBlock. Returns: BLock: """ prev_hash = UInt256(data=bytearray(32)) timestamp = int(datetime(2016, 7, 15, 15, 8, 21, tzinfo=pytz.utc).timestamp()) index = 0 consensus_data = 2083236893 # Pay tribute To Bitcoin next_consensus = Blockchain.GetConsensusAddress(Blockchain.StandbyValidators()) script = Witness(bytearray(0), bytearray(PUSHT)) mt = MinerTransaction() mt.Nonce = 2083236893 output = TransactionOutput( Blockchain.SystemShare().Hash, Blockchain.SystemShare().Amount, Crypto.ToScriptHash(Contract.CreateMultiSigRedeemScript(int(len(Blockchain.StandbyValidators()) / 2) + 1, Blockchain.StandbyValidators())) ) it = IssueTransaction([], [output], [], [script]) return Block(prev_hash, timestamp, index, consensus_data, next_consensus, script, [mt, Blockchain.SystemShare(), Blockchain.SystemCoin(), it], True)
def execute(self, arguments): wallet = PromptData.Wallet if len(arguments) < 3: print("Please specify the minimum required parameters") return False pubkey_in_wallet = arguments[0] if not PromptUtils.is_valid_public_key(pubkey_in_wallet): print("Invalid public key format") return False key_script_hash = Crypto.ToScriptHash(pubkey_in_wallet, unhex=True) if not wallet.ContainsKeyHash(key_script_hash): print("Supplied first public key does not exist in own wallet.") return False try: min_signature_cnt = int(arguments[1]) except ValueError: print(f"Invalid minimum signature count value: {arguments[1]}") return False if min_signature_cnt < 1: print("Minimum signatures count cannot be lower than 1") return False # validate minimum required signing key count signing_keys = arguments[2:] len_signing_keys = len(signing_keys) if len_signing_keys < min_signature_cnt: # we need at least 2 public keys in total otherwise it's just a regular address. # 1 pub key is from an address in our own wallet, a secondary key can come from any place. print( f"Missing remaining signing keys. Minimum required: {min_signature_cnt} given: {len_signing_keys}" ) return False # validate remaining pub keys for key in signing_keys: if not PromptUtils.is_valid_public_key(key): print(f"Invalid signing key {key}") return False signing_keys.append(pubkey_in_wallet) # validate that all signing keys are unique if len(signing_keys) > len(set(signing_keys)): print("Provided signing keys are not unique") return False verification_contract = Contract.CreateMultiSigContract( key_script_hash, min_signature_cnt, signing_keys) address = verification_contract.Address wallet.AddContract(verification_contract) print(f"Added multi-sig contract address {address} to wallet") return True
def ScriptHash(self): if self._scriptHash is None: unhex = True if len(self.Script) == 35: unhex = False self._scriptHash = Crypto.ToScriptHash(self.Script, unhex=unhex) return self._scriptHash
def Contract_Create(self, engine): script = engine.EvaluationStack.Pop().GetByteArray() if len(script) > 1024 * 1024: return False param_list = engine.EvaluationStack.Pop().GetByteArray() if len(param_list) > 252: return False return_type = int(engine.EvaluationStack.Pop().GetBigInteger()) contract_properties = int(engine.EvaluationStack.Pop().GetBigInteger()) if len(engine.EvaluationStack.Peek().GetByteArray()) > 252: return False name = engine.EvaluationStack.Pop().GetByteArray() if len(engine.EvaluationStack.Peek().GetByteArray()) > 252: return False code_version = engine.EvaluationStack.Pop().GetByteArray() if len(engine.EvaluationStack.Peek().GetByteArray()) > 252: return False author = engine.EvaluationStack.Pop().GetByteArray() if len(engine.EvaluationStack.Peek().GetByteArray()) > 252: return False email = engine.EvaluationStack.Pop().GetByteArray() if len(engine.EvaluationStack.Peek().GetByteArray()) > 65536: return False description = engine.EvaluationStack.Pop().GetByteArray() hash = Crypto.ToScriptHash(script, unhex=False) contract = self._contracts.TryGet(hash.ToBytes()) if contract is None: code = FunctionCode(script=script, param_list=param_list, return_type=return_type, contract_properties=contract_properties) contract = ContractState(code, contract_properties, name, code_version, author, email, description) self._contracts.GetAndChange(code.ScriptHash().ToBytes(), contract) self._contracts_created[hash.ToBytes()] = UInt160(data=engine.CurrentContext.ScriptHash()) engine.EvaluationStack.PushT(StackItem.FromInterface(contract)) # logger.info("*****************************************************") # logger.info("CREATED CONTRACT %s " % hash.ToBytes()) # logger.info("*****************************************************") return True
def is_valid_public_key(key): if len(key) != 66: return False try: Crypto.ToScriptHash(key, unhex=True) except Exception: # the UINT160 inside ToScriptHash can throw Exception return False else: return True
def GetAddress(self): """ Returns the public NEO address for this KeyPair Returns: str: The private key """ script = b'21' + self.PublicKey.encode_point(True) + b'ac' script_hash = Crypto.ToScriptHash(script) address = Crypto.ToAddress(script_hash) return address
def ScriptHash(self): """ Get the script hash. Returns: UInt160: """ if self._scriptHash is None: self._scriptHash = Crypto.ToScriptHash(self.Script, unhex=False) return self._scriptHash
def ContainsKey(self, public_key): """ Test if the wallet contains the supplied public key. Args: public_key (edcsa.Curve.point): a public key to test for its existance. i.e. KeyPair.PublicKey Returns: bool: True if exists, False otherwise. """ return self.ContainsKeyHash(Crypto.ToScriptHash(public_key.encode_point(True), unhex=True))
def GetConsensusAddress(validators): """ Get the script hash of the consensus node. Args: validators (list): of Ellipticcurve.ECPoint's Returns: UInt160: """ vlen = len(validators) script = Contract.CreateMultiSigRedeemScript(vlen - int((vlen - 1) / 3), validators) return Crypto.ToScriptHash(script)
def SystemShare(): """ Register AntShare. Returns: RegisterTransaction: """ amount = Fixed8.FromDecimal(sum(Blockchain.GENERATION_AMOUNT) * Blockchain.DECREMENT_INTERVAL) owner = ECDSA.secp256r1().Curve.Infinity admin = Crypto.ToScriptHash(PUSHT) return RegisterTransaction([], [], AssetType.GoverningToken, "[{\"lang\":\"zh-CN\",\"name\":\"小蚁股\"},{\"lang\":\"en\",\"name\":\"AntShare\"}]", amount, 0, owner, admin)
def claim_initial_neo(self, target_address): wallets = [] i = 0 tx_json = None dbloops = [] print("Signing new transaction with 3 of 4 node keys...") for pkey, wif in nodekeys.items(): walletpath = "wallet{}.db3".format(i + 1) if os.path.exists(walletpath): os.remove(walletpath) wallet = UserWallet.Create(path=walletpath, password=to_aes_key(self.wallet_pwd)) wallets.append(wallet) print("Importing node private key to to {}".format(walletpath)) prikey = KeyPair.PrivateKeyFromWIF(wif) wallet.CreateKey(prikey) print("Importing multi-sig contract to {}".format(walletpath)) keys = list(nodekeys.keys()) pubkey_script_hash = Crypto.ToScriptHash(pkey, unhex=True) verification_contract = Contract.CreateMultiSigContract( pubkey_script_hash, 3, keys) wallet.AddContract(verification_contract) print("Added multi-sig contract address %s to wallet" % verification_contract.Address) dbloop = task.LoopingCall(wallet.ProcessBlocks) dbloop.start(1) dbloops.append(dbloop) # print("Wallet %s " % json.dumps(wallet.ToJson(), indent=4)) if i == 0: print( "Creating spend transaction to {}".format(target_address)) tx_json = self.send_neo(wallet, multisig_addr, target_address, '100000000') if tx_json is None: break else: tx_json = self.sign_and_finish(wallet, tx_json) if tx_json == 'success': print( "Finished, {} should now own all the NEO on the private network." .format(target_address)) break i += 1
def CreateSignatureContract(publicKey): """ Create a signature contract. Args: publicKey (edcsa.Curve.point): e.g. KeyPair.PublicKey. Returns: neo.SmartContract.Contract: a Contract instance. """ script = Contract.CreateSignatureRedeemScript(publicKey) params = b'\x00' encoded = publicKey.encode_point(True) pubkey_hash = Crypto.ToScriptHash(encoded, unhex=True) return Contract(script, params, pubkey_hash)
def SystemCoin(): """ Register AntCoin Returns: RegisterTransaction: """ amount = Fixed8.FromDecimal(sum(Blockchain.GENERATION_AMOUNT) * Blockchain.DECREMENT_INTERVAL) owner = ECDSA.secp256r1().Curve.Infinity precision = 8 admin = Crypto.ToScriptHash(PUSHF) return RegisterTransaction([], [], AssetType.UtilityToken, "[{\"lang\":\"zh-CN\",\"name\":\"小蚁币\"},{\"lang\":\"en\",\"name\":\"AntCoin\"}]", amount, precision, owner, admin)
def ImportContractAddr(wallet, args): if wallet is None: print("please open a wallet") return contract_hash = get_arg(args, 0) pubkey = get_arg(args, 1) if contract_hash and pubkey: if len(pubkey) != 66: print("invalid public key format") pubkey_script_hash = Crypto.ToScriptHash(pubkey, unhex=True) contract = Blockchain.Default().GetContract(contract_hash) if contract is not None: reedeem_script = contract.Code.Script.hex() # there has to be at least 1 param, and the first # one needs to be a signature param param_list = bytearray(b'\x00') # if there's more than one param # we set the first parameter to be the signature param if len(contract.Code.ParameterList) > 1: param_list = bytearray(contract.Code.ParameterList) param_list[0] = 0 verification_contract = Contract.Create(reedeem_script, param_list, pubkey_script_hash) address = verification_contract.Address wallet.AddContract(verification_contract) print("Added contract addres %s to wallet" % address) return print("Could not add contract. Invalid public key or contract address")
def make_multisig(target_pubkey, wallet): wallets = [] i = 0 tx_json = None dbloops = [] pubkey = wallet.PubKeys()[0]['Public Key'] multisig_args = [pubkey, 1, target_pubkey, pubkey] pubkey = multisig_args[0] m = multisig_args[1] publicKeys = multisig_args[2:] pubkey_script_hash = Crypto.ToScriptHash(pubkey, unhex=True) verification_contract = Contract.CreateMultiSigContract( pubkey_script_hash, int(m), publicKeys) address = verification_contract.Address wallet.AddContract(verification_contract) print("Added multi-sig contract address %s to wallet" % address) return address
def __init__(self, priv_key): """ Create an instance. Args: priv_key (bytes): a private key. """ self.setup_curve() length = len(priv_key) if length != 32 and length != 96 and length != 104: raise ValueError("Invalid private key") self.PrivateKey = bytearray(priv_key[-32:]) pubkey_encoded_not_compressed = None if length == 32: try: pubkey_encoded_not_compressed = bitcoin.privkey_to_pubkey( priv_key) except Exception as e: raise Exception("Could not determine public key") elif length == 96 or length == 104: skip = length - 96 pubkey_encoded_not_compressed = bytearray(b'\x04') + bytearray( priv_key[skip:skip + 64]) if pubkey_encoded_not_compressed: pubkey_points = bitcoin.decode_pubkey( pubkey_encoded_not_compressed, 'bin') pubx = pubkey_points[0] puby = pubkey_points[1] edcsa = ECDSA.secp256r1() self.PublicKey = edcsa.Curve.point(pubx, puby) self.PublicKeyHash = Crypto.ToScriptHash( self.PublicKey.encode_point(True), unhex=True)
def execute(self, arguments): wallet = PromptData.Wallet if len(arguments) != 2: print("Please specify the required parameters") return try: contract_hash = UInt160.ParseString(arguments[0]).ToBytes() except Exception: print(f"Invalid contract hash: {arguments[0]}") return pubkey = arguments[1] if not PromptUtils.is_valid_public_key(pubkey): print(f"Invalid pubkey: {arguments[1]}") return pubkey_script_hash = Crypto.ToScriptHash(pubkey, unhex=True) return ImportContractAddr(wallet, contract_hash, pubkey_script_hash)
def test_issue_tx(self): miner_tx = MinerTransaction() miner_tx.Nonce = 2083236893 share_tx = GetSystemShare() coin_tx = GetSystemCoin() script = Contract.CreateMultiSigRedeemScript( int(len(Blockchain.StandbyValidators()) / 2) + 1, Blockchain.StandbyValidators()) if settings.MAGIC == 1953787457: self.assertEqual(script, self.contractraw) out = Crypto.ToScriptHash(script) output = TransactionOutput(share_tx.Hash, Blockchain.SystemShare().Amount, out) script = Witness(bytearray(0), bytearray(PUSHT)) issue_tx = IssueTransaction([], [output], [], [script]) self.assertEqual(issue_tx.GetHashData(), self.issuetx_rraw) self.assertEqual(issue_tx.Hash.ToBytes(), self.gen_issue_tx_id)
def test_deploy_and_invoke(deploy_script, invoke_args, wallet, from_addr=None, min_fee=DEFAULT_MIN_FEE, invocation_test_mode=True, debug_map=None): bc = GetBlockchain() sn = bc._db.snapshot() accounts = DBCollection(bc._db, sn, DBPrefix.ST_Account, AccountState) assets = DBCollection(bc._db, sn, DBPrefix.ST_Asset, AssetState) validators = DBCollection(bc._db, sn, DBPrefix.ST_Validator, ValidatorState) contracts = DBCollection(bc._db, sn, DBPrefix.ST_Contract, ContractState) storages = DBCollection(bc._db, sn, DBPrefix.ST_Storage, StorageItem) if settings.USE_DEBUG_STORAGE: debug_storage = DebugStorage.instance() debug_sn = debug_storage.db.snapshot() storages = DBCollection(debug_storage.db, debug_sn, DBPrefix.ST_Storage, StorageItem) storages.DebugStorage = True dtx = InvocationTransaction() dtx.Version = 1 dtx.outputs = [] dtx.inputs = [] dtx.scripts = [] dtx.Script = binascii.unhexlify(deploy_script) if from_addr is not None: from_addr = lookup_addr_str(wallet, from_addr) dtx = wallet.MakeTransaction(tx=dtx, from_addr=from_addr) context = ContractParametersContext(dtx) wallet.Sign(context) dtx.scripts = context.GetScripts() script_table = CachedScriptTable(contracts) service = StateMachine(accounts, validators, assets, contracts, storages, None) contract = wallet.GetDefaultContract() dtx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=Crypto.ToScriptHash(contract.Script, unhex=False)) ] to_dispatch = [] engine = ApplicationEngine(trigger_type=TriggerType.Application, container=dtx, table=script_table, service=service, gas=dtx.Gas, testMode=True) engine.LoadScript(dtx.Script, False) # first we will execute the test deploy # then right after, we execute the test invoke d_success = engine.Execute() if d_success: items = engine.EvaluationStack.Items contract_state = None for i in items: if type(i) is ContractState: contract_state = i break elif type(i) is InteropInterface: item = i.GetInterface() if type(item) is ContractState: contract_state = item break shash = contract_state.Code.ScriptHash() invoke_args, neo_to_attach, gas_to_attach = get_asset_attachments( invoke_args) invoke_args.reverse() # print("neo, gas %s %s " % (neo_to_attach,gas_to_attach.ToString())) sb = ScriptBuilder() for p in invoke_args: item = parse_param(p, wallet) if type(item) is list: item.reverse() listlength = len(item) for listitem in item: subitem = parse_param(listitem, wallet) sb.push(subitem) sb.push(listlength) sb.Emit(PACK) else: sb.push(item) sb.EmitAppCall(shash.Data) out = sb.ToArray() outputs = [] if neo_to_attach: output = TransactionOutput( AssetId=Blockchain.SystemShare().Hash, Value=neo_to_attach, script_hash=contract_state.Code.ScriptHash(), ) outputs.append(output) if gas_to_attach: output = TransactionOutput( AssetId=Blockchain.SystemCoin().Hash, Value=gas_to_attach, script_hash=contract_state.Code.ScriptHash()) outputs.append(output) itx = InvocationTransaction() itx.Version = 1 itx.outputs = outputs itx.inputs = [] itx.scripts = [] itx.Attributes = [] itx.Script = binascii.unhexlify(out) if len(outputs) < 1: contract = wallet.GetDefaultContract() itx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=Crypto.ToScriptHash( contract.Script, unhex=False).Data) ] itx = wallet.MakeTransaction(tx=itx, from_addr=from_addr) context = ContractParametersContext(itx) wallet.Sign(context) itx.scripts = context.GetScripts() # print("tx: %s " % json.dumps(itx.ToJson(), indent=4)) engine = ApplicationEngine(trigger_type=TriggerType.Application, container=itx, table=script_table, service=service, gas=itx.Gas, testMode=invocation_test_mode) engine.LoadScript(itx.Script, False) engine.LoadDebugInfo(debug_map) # call execute in its own blocking thread # reactor.stop() i_success = engine.Execute() service.ExecutionCompleted(engine, i_success) to_dispatch = to_dispatch + service.events_to_dispatch for event in to_dispatch: events.emit(event.event_type, event) if i_success: service.TestCommit() if len(service.notifications) > 0: for n in service.notifications: # print("NOTIFICATION : %s " % n) Blockchain.Default().OnNotify(n) logger.info("Used %s Gas " % engine.GasConsumed().ToString()) consumed = engine.GasConsumed() - Fixed8.FromDecimal(10) consumed = consumed.Ceil() if consumed <= Fixed8.Zero(): consumed = min_fee total_ops = engine.ops_processed # set the amount of gas the tx will need itx.Gas = consumed itx.Attributes = [] result = engine.EvaluationStack.Items return itx, result, total_ops, engine else: print("error executing invoke contract...") else: print("error executing deploy contract.....") service.ExecutionCompleted(engine, False, 'error') return None, [], 0, None
def construct_invoke_tx(wallet, params): params = params[0] from_addr = params['from_addr'] BC = GetBlockchain() contract = BC.GetContract(params['addr']) if not contract: raise Exception('no such contract') neo_to_attach = params.get('neo_to_attach', 0) gas_to_attach = params.get('gas_to_attach', 0) sb = ScriptBuilder() contract_parameters = [ContractParameter.FromJson(p) for p in params['contract_params']] sb.EmitAppCallWithJsonArgs(contract.Code.ScriptHash(), contract_parameters) invoke_script = sb.ToArray() outputs = [] if neo_to_attach: output = TransactionOutput(AssetId=Blockchain.SystemShare().Hash, Value=neo_to_attach, script_hash=contract.Code.ScriptHash(), ) outputs.append(output) if gas_to_attach: output = TransactionOutput(AssetId=Blockchain.SystemCoin().Hash, Value=gas_to_attach, script_hash=contract.Code.ScriptHash(), ) outputs.append(output) bc = GetBlockchain() sn = bc._db.snapshot() accounts = DBCollection(bc._db, DBPrefix.ST_Account, AccountState) assets = DBCollection(bc._db, DBPrefix.ST_Asset, AssetState) validators = DBCollection(bc._db, DBPrefix.ST_Validator, ValidatorState) contracts = DBCollection(bc._db, DBPrefix.ST_Contract, ContractState) storages = DBCollection(bc._db, DBPrefix.ST_Storage, StorageItem) tx = InvocationTransaction() tx.outputs = outputs tx.inputs = [] tx.Version = 1 tx.scripts = [] tx.Script = binascii.unhexlify(invoke_script) script_table = CachedScriptTable(contracts) service = StateMachine(accounts, validators, assets, contracts, storages, None) contract = wallet.GetDefaultContract() tx.Attributes = [TransactionAttribute(usage=TransactionAttributeUsage.Script, data=Crypto.ToScriptHash(contract.Script, unhex=False).Data)] tx = wallet.MakeTransaction(tx=tx) engine = ApplicationEngine( trigger_type=TriggerType.Application, container=tx, table=script_table, service=service, gas=tx.Gas, testMode=True ) engine.LoadScript(tx.Script, False) success = engine.Execute() if not success: raise Exception('exec failed') service.ExecutionCompleted(engine, success) consumed = engine.GasConsumed() - Fixed8.FromDecimal(10) consumed = consumed.Ceil() net_fee = None tx_gas = None if consumed <= Fixed8.Zero(): net_fee = Fixed8.FromDecimal(.0001) tx_gas = Fixed8.Zero() else: tx_gas = consumed net_fee = Fixed8.Zero() tx.Gas = tx_gas tx.outputs = outputs tx.Attributes = [] # InvokeContract from_addr = lookup_addr_str(wallet, from_addr) tx = wallet.MakeTransaction(tx=tx, fee=net_fee, use_standard=True, from_addr=from_addr) if tx is None: raise Exception("no gas") context = ContractParametersContext(tx) ms = StreamManager.GetStream() writer = BinaryWriter(ms) tx.Serialize(writer) ms.flush() binary_tx = ms.ToArray() return {'context': context.ToJson(), 'tx': binary_tx.decode()}
def construct_deploy_tx(wallet, params): params = params[0] from_addr = params['from_addr'] # load_smart_contract contract_params = bytearray(binascii.unhexlify(params['contract_params'])) return_type = bytearray(binascii.unhexlify(params['return_type'])) contract_properties = 0 if params.get('needs_storage', True): contract_properties += ContractPropertyState.HasStorage if params.get('needs_dynamic_invoke', False): contract_properties += ContractPropertyState.HasDynamicInvoke script = binascii.unhexlify(params['bin']) function_code = FunctionCode( script = script, param_list = contract_params, return_type = return_type, contract_properties = contract_properties, ) if Blockchain.Default().GetContract(function_code.ScriptHash().To0xString()): raise Exception('contract already exists') # GatherContractDetails details = params['details'] name = details['name'] version = details['version'] author = details['author'] email = details['email'] description = details['description'] contract_script = generate_deploy_script( function_code.Script, name, version, author, email, description, function_code.ContractProperties, function_code.ReturnType, function_code.ParameterList, ) # test_invoke bc = GetBlockchain() sn = bc._db.snapshot() accounts = DBCollection(bc._db, DBPrefix.ST_Account, AccountState) assets = DBCollection(bc._db, DBPrefix.ST_Asset, AssetState) validators = DBCollection(bc._db, DBPrefix.ST_Validator, ValidatorState) contracts = DBCollection(bc._db, DBPrefix.ST_Contract, ContractState) storages = DBCollection(bc._db, DBPrefix.ST_Storage, StorageItem) tx = InvocationTransaction() tx.outputs = [] tx.inputs = [] tx.Version = 1 tx.scripts = [] tx.Script = binascii.unhexlify(contract_script) script_table = CachedScriptTable(contracts) service = StateMachine(accounts, validators, assets, contracts, storages, None) contract = wallet.GetDefaultContract() tx.Attributes = [TransactionAttribute(usage=TransactionAttributeUsage.Script, data=Crypto.ToScriptHash(contract.Script, unhex=False).Data)] tx = wallet.MakeTransaction(tx=tx) engine = ApplicationEngine( trigger_type=TriggerType.Application, container=tx, table=script_table, service=service, gas=tx.Gas, testMode=True ) engine.LoadScript(tx.Script, False) success = engine.Execute() if not success: raise Exception('exec failed') service.ExecutionCompleted(engine, success) consumed = engine.GasConsumed() - Fixed8.FromDecimal(10) consumed = consumed.Ceil() net_fee = None tx_gas = None if consumed <= Fixed8.Zero(): net_fee = Fixed8.FromDecimal(.0001) tx_gas = Fixed8.Zero() else: tx_gas = consumed net_fee = Fixed8.Zero() tx.Gas = tx_gas tx.outputs = [] tx.Attributes = [] # InvokeContract from_addr = lookup_addr_str(wallet, from_addr) tx = wallet.MakeTransaction(tx=tx, fee=net_fee, use_standard=True, from_addr=from_addr) if tx is None: raise Exception("no gas") context = ContractParametersContext(tx) ms = StreamManager.GetStream() writer = BinaryWriter(ms) tx.Serialize(writer) ms.flush() binary_tx = ms.ToArray() return {'context': context.ToJson(), 'tx': binary_tx.decode(), 'hash': function_code.ScriptHash().To0xString()}
def neo_get_scripthash_from_private_key(private_key): script = b'21' + neo_get_public_key_from_private_key( private_key).encode_point(True) + b'ac' return Crypto.ToScriptHash(data=script)
def CheckWitnessPubkey(self, engine, pubkey): scripthash = Contract.CreateSignatureRedeemScript(pubkey) return self.CheckWitnessHash(engine, Crypto.ToScriptHash(scripthash))