def GetScripts(self): if not self.Completed: raise Exception("Signature Context not complete") scripts = [] for i in range(0, len(self.ScriptHashes)): item = self.ContextItems[self.ScriptHashes[i].ToBytes()] print("GETTING SCRIPTS, item is %s " % item) sb = ScriptBuilder() plist = list(item.ContractParameters) plist.reverse() for p in plist: sb.push(p.Value) vscript = bytearray(0) if item.Script is not None: vscript = item.Script witness = Witness( invocation_script=sb.ToArray(), verification_script=vscript ) scripts.append(witness) return scripts
def Transfer(self, wallet, from_addr, to_addr, amount, tx_attributes=None): """ Transfer a specified amount of the NEP5Token to another address. Args: wallet (neo.Wallets.Wallet): a wallet instance. from_addr (str): public address of the account to transfer the given amount from. to_addr (str): public address of the account to transfer the given amount to. amount (int): quantity to send. tx_attributes (list): a list of TransactionAtribute objects. Returns: tuple: InvocationTransaction: the transaction. int: the transaction fee. list: the neo VM evaluationstack results. """ if not tx_attributes: tx_attributes = [] sb = ScriptBuilder() sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'transfer', [parse_param(from_addr, wallet), parse_param(to_addr, wallet), parse_param(amount)]) tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, [], from_addr=from_addr, invoke_attrs=tx_attributes) return tx, fee, results
def runRawTransaction(operation, args): invocation_tx = InvocationTransaction() smartcontract_scripthash = UInt160.ParseString(CONTRACT_HASH) sb = ScriptBuilder() sb.EmitAppCallWithOperationAndArgs( smartcontract_scripthash, operation, args) invocation_tx.Script = binascii.unhexlify(sb.ToArray()) wallet = UserWallet.Create( 'neo-privnet.wallet', to_aes_key('coz'), generate_default_key=False) private_key = KeyPair.PrivateKeyFromWIF( "KxDgvEKzgSBPPfuVfw67oPQBSjidEiqTHURKSDL1R7yGaGYAeYnr") wallet.CreateKey(private_key) context = ContractParametersContext(invocation_tx) wallet.Sign(context) invocation_tx.scripts = context.GetScripts() raw_tx = invocation_tx.ToArray() payload = {"jsonrpc": "2.0", "id": 1, "method": "sendrawtransaction", "params": [raw_tx.decode("ascii")]} res = requests.post( "http://neo-nodes:30333/testNeoConnection", json=payload) print("received POST result") print(res.status_code) result = res.text print(result) return result
def GetBalance(self, wallet, address, as_string=False): """ Get the token balance. Args: wallet (neo.Wallets.Wallet): a wallet instance. address (str): public address of the account to get the token balance of. as_string (bool): whether the return value should be a string. Default is False, returning an integer. Returns: int/str: token balance value as int (default), token balanace as string if `as_string` is set to True. 0 if balance retrieval failed. """ addr = parse_param(address, wallet) if isinstance(addr, UInt160): addr = addr.Data sb = ScriptBuilder() sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'balanceOf', [addr]) tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, []) try: val = results[0].GetBigInteger() precision_divisor = pow(10, self.decimals) balance = Decimal(val) / Decimal(precision_divisor) if as_string: formatter_str = '.%sf' % self.decimals balance_str = format(balance, formatter_str) return balance_str return balance except Exception as e: logger.error("could not get balance: %s " % e) traceback.print_stack() return 0
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 create_raw_sc_method_call_tx( source_address, source_address_wif, smartcontract_scripthash, smartcontract_method, smartcontract_method_args, ): source_script_hash = address_to_scripthash(source_address) # start by creating a base InvocationTransaction # the inputs, outputs and Type do not have to be set anymore. invocation_tx = InvocationTransaction() # often times smart contract developers use the function ``CheckWitness`` to determine if the transaction is signed by somebody eligible of calling a certain method # in order to pass that check you want to add the corresponding script_hash as a transaction attribute (this is generally the script_hash of the public key you use for signing) # Note that for public functions like the NEP-5 'getBalance' and alike this would not be needed, but it doesn't hurt either invocation_tx.Attributes.append( TransactionAttribute(usage=TransactionAttributeUsage.Script, data=source_script_hash)) smartcontract_scripthash = UInt160.ParseString(smartcontract_scripthash) # next we need to build a 'script' that gets executed against the smart contract. # this is basically the script that calls the entry point of the contract with the necessary parameters sb = ScriptBuilder() # call the method on the contract (assumes contract address is a NEP-5 token) sb.EmitAppCallWithOperationAndArgs( smartcontract_scripthash, smartcontract_method, smartcontract_method_args, ) invocation_tx.Script = binascii.unhexlify(sb.ToArray()) # at this point we've build our unsigned transaction and it's time to sign it before we get the raw output that we can send to the network via RPC # we need to create a Wallet instance for helping us with signing wallet = UserWallet.Create('path', to_aes_key('mypassword'), generate_default_key=False) # if you have a WIF use the following # this WIF comes from the `neo-test1-w.wallet` fixture wallet private_key = KeyPair.PrivateKeyFromWIF(source_address_wif) # if you have a NEP2 encrypted key use the following instead # private_key = KeyPair.PrivateKeyFromNEP2("NEP2 key string", "password string") # we add the key to our wallet wallet.CreateKey(private_key) # and now we're ready to sign context = ContractParametersContext(invocation_tx) wallet.Sign(context) invocation_tx.scripts = context.GetScripts() raw_tx = invocation_tx.ToArray() print(raw_tx) return raw_tx.decode()
def GetWithdrawalBalance(wallet, contract_hash, from_addr, asset_type): sb = ScriptBuilder() sb.EmitAppCallWithOperationAndData(contract_hash, 'balance_%s' % asset_type, from_addr) try: tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, []) return results[0].GetBigInteger() except Exception as e: print("could not get balance: %s " % e)
def CreateMultiSigRedeemScript(m, publicKeys): if m < 1: raise Exception("Minimum required signature count is 1, specified {}.".format(m)) if m > len(publicKeys): raise Exception("Invalid public key count. Minimum required signatures is bigger than supplied public keys count.") if len(publicKeys) > 1024: raise Exception("Supplied public key count ({}) exceeds maximum of 1024.".format(len(publicKeys))) sb = ScriptBuilder() sb.push(m) pkeys = [point for point in publicKeys] pkeys.sort() keys = [p.encode_point().decode() for p in pkeys] for key in keys: sb.push(key) sb.push(len(publicKeys)) sb.add(CHECKMULTISIG) return sb.ToArray()
def TestInvokeContract(wallet, args, withdrawal_tx=None, from_addr=None, min_fee=DEFAULT_MIN_FEE, invoke_attrs=None, owners=None): BC = GetBlockchain() contract = BC.GetContract(args[0]) if contract: # params = args[1:] if len(args) > 1 else [] params, neo_to_attach, gas_to_attach = PromptUtils.get_asset_attachments(params) params, parse_addresses = PromptUtils.get_parse_addresses(params) params.reverse() if '--i' in params: params = [] for index, iarg in enumerate(contract.Code.ParameterList): param, abort = PromptUtils.gather_param(index, iarg) if abort: return None, None, None, None, False params.append(param) params.reverse() sb = ScriptBuilder() for p in params: process_params(sb, p, wallet, parse_addresses) sb.EmitAppCall(contract.Code.ScriptHash().Data) out = 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) return test_invoke(out, wallet, outputs, withdrawal_tx, from_addr, min_fee, invoke_attrs=invoke_attrs, owners=owners) else: print("Contract %s not found" % args[0]) return None, None, None, None, False
def example2(): source_address = "AJQ6FoaSXDFzA6wLnyZ1nFN7SGSN2oNTc3" source_script_hash = address_to_scripthash(source_address) # start by creating a base InvocationTransaction # the inputs, outputs and Type do not have to be set anymore. invocation_tx = InvocationTransaction() # Since we are building a raw transaction, we will add the raw_tx flag invocation_tx.raw_tx = True # often times smart contract developers use the function ``CheckWitness`` to determine if the transaction is signed by somebody eligible of calling a certain method # in order to pass that check you want to add the corresponding script_hash as a transaction attribute (this is generally the script_hash of the public key you use for signing) # Note that for public functions like the NEP-5 'getBalance' and alike this would not be needed, but it doesn't hurt either invocation_tx.Attributes.append( TransactionAttribute(usage=TransactionAttributeUsage.Script, data=source_script_hash)) # next we need to build a 'script' that gets executed against the smart contract. # this is basically the script that calls the entry point of the contract with the necessary parameters smartcontract_scripthash = UInt160.ParseString( "31730cc9a1844891a3bafd1aa929a4142860d8d3") sb = ScriptBuilder() # call the NEP-5 `name` method on the contract (assumes contract address is a NEP-5 token) sb.EmitAppCallWithOperation(smartcontract_scripthash, 'name') invocation_tx.Script = binascii.unhexlify(sb.ToArray()) # at this point we've build our unsigned transaction and it's time to sign it before we get the raw output that we can send to the network via RPC # we need to create a Wallet instance for helping us with signing wallet = UserWallet.Create('path', to_aes_key('mypassword'), generate_default_key=False) # if you have a WIF use the following # this WIF comes from the `neo-test1-w.wallet` fixture wallet private_key = KeyPair.PrivateKeyFromWIF( "Ky94Rq8rb1z8UzTthYmy1ApbZa9xsKTvQCiuGUZJZbaDJZdkvLRV") # if you have a NEP2 encrypted key use the following instead # private_key = KeyPair.PrivateKeyFromNEP2("NEP2 key string", "password string") # we add the key to our wallet wallet.CreateKey(private_key) # and now we're ready to sign context = ContractParametersContext(invocation_tx) wallet.Sign(context) invocation_tx.scripts = context.GetScripts() raw_tx = invocation_tx.ToArray() return raw_tx
def VerifyScripts(verifiable): try: hashes = verifiable.GetScriptHashesForVerifying() except Exception as e: logger.error("couldn't get script hashes %s " % e) return False if len(hashes) != len(verifiable.Scripts): return False state_reader = GetStateReader() blockchain = GetBlockchain() for i in range(0, len(hashes)): verification = verifiable.Scripts[i].VerificationScript if len(verification) == 0: # logger.info("VERIFICATION IS 0, EMITTING APP CALL") sb = ScriptBuilder() sb.EmitAppCall(hashes[i].Data) verification = sb.ToArray() else: verification_hash = Crypto.ToScriptHash(verification, unhex=False) if hashes[i] != verification_hash: return False engine = ApplicationEngine(TriggerType.Verification, verifiable, blockchain, state_reader, Fixed8.Zero()) engine.LoadScript(verification, False) invoction = verifiable.Scripts[i].InvocationScript engine.LoadScript(invoction, True) try: success = engine.Execute() state_reader.ExecutionCompleted(engine, success) except Exception as e: state_reader.ExecutionCompleted(engine, False, e) # pdb.set_trace() if engine.EvaluationStack.Count != 1 or not engine.EvaluationStack.Pop( ).GetBoolean(): return False return True
def VerifyScripts(verifiable): try: hashes = verifiable.GetScriptHashesForVerifying() except Exception as e: print("couldng get script hashes %s " % e) return False if len(hashes) != len(verifiable.Scripts): print("hashes not same length as verifiable scripts") return False print("hello!!!! %s " % hashes) for i in range(0, len(hashes)): verification = verifiable.Scripts[i].VerificationScript print("verifying script: %s %s " % (hashes[i], verification)) if len(verification) == 0: sb = ScriptBuilder() sb.EmitAppCall(hashes[i].Data) verification = sb.ToArray() else: if hashes[i] != verification: print("hashes not equal to script hash!") return False engine = ApplicationEngine(TriggerType.Verification, verifiable, GetBlockchain(), GetStateReader(), Fixed8.Zero()) engine.LoadScript(verification, False) engine.LoadScript(verifiable.Scripts[i].InvocationScript, True) res = engine.Execute() if not res: print("engine did not execune") return False else: print("engine did execute!") if engine.EvaluationStack.Count != 1 or not engine.EvaluationStack.Pop( ).GetBoolean(): print("stack not one, or stack false") return False return True
def CancelWithdrawalHolds(wallet, contract_hash, require_password=True): wallet.LoadHolds() to_cancel = [] for hold in wallet._holds: if hold.FromAddress == contract_hash: to_cancel.append(hold) if len(to_cancel) < 1: print("No holds to cancel") return sb = ScriptBuilder() for hold in to_cancel: sb.EmitAppCallWithOperationAndData(hold.InputHash, 'cancel_hold', hold.Vin) try: tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, []) for i in results: if not i.GetBoolean(): print("Error executing hold cleanup") return if require_password: print( "\n---------------------------------------------------------------" ) print("Will cancel %s holds" % len(to_cancel)) print("FEE IS %s " % fee.ToString()) print("GAS IS %s " % tx.Gas.ToString()) print( "------------------------------------------------------------------\n" ) print("Enter your password to complete this request") passwd = prompt("[Password]> ", is_password=True) if not wallet.ValidatePassword(passwd): print("incorrect password") return result = InvokeContract(wallet, tx, fee) return result except Exception as e: print("could not cancel hold(s): %s " % e)
def CleanupCompletedHolds(wallet, require_password=True): completed = wallet.LoadCompletedHolds() if len(completed) < 1: print("No holds to cleanup") return False sb = ScriptBuilder() for hold in completed: sb.EmitAppCallWithOperationAndData(hold.InputHash, 'cleanup_hold', hold.Vin) try: tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, []) for i in results: if not i.GetBoolean(): print("Error executing hold cleanup") return False if require_password: print( "\n---------------------------------------------------------------" ) print("Will cleanup %s holds" % len(completed)) print("FEE IS %s " % fee.ToString()) print("GAS IS %s " % tx.Gas.ToString()) print( "------------------------------------------------------------------\n" ) print("Enter your password to complete this request") passwd = prompt("[Password]> ", is_password=True) if not wallet.ValidatePassword(passwd): print("incorrect password") return result = InvokeContract(wallet, tx, fee) return result except Exception as e: print("could not cancel hold(s): %s " % e) return False
def GetScripts(self): if not self.Completed: raise Exception("Signature Context not complete") scripts = [] for i in range(0, len(self.ScriptHashes)): item = self.ContextItems[self.ScriptHashes[i].ToBytes()] sb = ScriptBuilder() plist = list(item.ContractParameters) plist.reverse() for p in plist: if type(p.Value) is list: pa = p.Value pa.reverse() listlength = len(pa) for listitem in pa: sb.push(listitem) sb.push(listlength) sb.Emit(OpCode.PACK) else: sb.push(p.Value) vscript = bytearray(0) if item.Script is not None: if type(item.Script) is str: item.Script = item.Script.encode('utf-8') vscript = item.Script # logger.info("SCRIPT IS %s " % item.Script) witness = Witness( invocation_script=sb.ToArray(), verification_script=vscript ) scripts.append(witness) return scripts
def GetScripts(self): if not self.Completed: raise Exception("Signature Context not complete") scripts = [] for i in range(0, len(self.ScriptHashes)): item = self.ContextItems[self.ScriptHashes[i].ToBytes()] sb = ScriptBuilder() plist = list(item.ContractParameters) plist.reverse() for p in plist: if type(p.Value) is list: pa = p.Value pa.reverse() listlength = len(pa) for listitem in pa: sb.push(listitem) sb.push(listlength) sb.Emit(OpCode.PACK) else: sb.push(p.Value) vscript = bytearray(0) if item.Script is not None: if type(item.Script) is str: item.Script = item.Script.encode('utf-8') vscript = item.Script # logger.info("SCRIPT IS %s " % item.Script) witness = Witness( # invocation_script='40fdb984faf0a400b6894c1ce5b317cf894ba3eb89b899cefda2ac307b278418b943534ad298884f9200dc4b7e1dc244db16c62a44a830a860060ec11d3e6e9717', invocation_script=sb.ToArray(), verification_script=vscript) scripts.append(witness) return scripts
def GetBalance(self, wallet, address, as_string=False): """ Get the token balance. Args: wallet (neo.Wallets.Wallet): a wallet instance. address (str): public address of the account to get the token balance of. as_string (bool): whether the return value should be a string. Default is False, returning an integer. Returns: int/str: token balance value as int (default), token balanace as string if `as_string` is set to True. 0 if balance retrieval failed. """ addr = PromptUtils.parse_param(address, wallet) if isinstance(addr, UInt160): addr = addr.Data sb = ScriptBuilder() sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'balanceOf', [addr]) tx, fee, results, num_ops, engine_success = test_invoke( sb.ToArray(), wallet, []) if engine_success: try: val = results[0].GetBigInteger() precision_divisor = pow(10, self.decimals) balance = Decimal(val) / Decimal(precision_divisor) if as_string: formatter_str = '.%sf' % self.decimals balance_str = format(balance, formatter_str) return balance_str return balance except Exception as e: logger.error("could not get balance: %s " % e) traceback.print_stack() else: addr_str = Crypto.ToAddress(UInt160(data=addr)) logger.error( f"Could not get balance of address {addr_str} for token contract {self.ScriptHash}. VM execution failed. Make sure the contract exists on the network and that it adheres to the NEP-5 standard" ) return 0
def Query(self, wallet): """ Query the smart contract for its token information (name, symbol, decimals). Args: wallet (neo.Wallets.Wallet): a wallet instance. Returns: None: if the NEP5Token instance `Name` is already set. True: if all information was retrieved. False: if information retrieval failed. """ if self.name is not None: # don't query twice return sb = ScriptBuilder() sb.EmitAppCallWithOperation(self.ScriptHash, 'name') sb.EmitAppCallWithOperation(self.ScriptHash, 'symbol') sb.EmitAppCallWithOperation(self.ScriptHash, 'decimals') tx, fee, results, num_ops = test_invoke(sb.ToArray(), wallet, []) try: self.name = results[0].GetString() self.symbol = results[1].GetString() self.decimals = results[2].GetBigInteger() return True except Exception as e: logger.error("could not query token %s " % e) return False
def Query(self): """ Query the smart contract for its token information (name, symbol, decimals). Args: wallet (neo.Wallets.Wallet): a wallet instance. Returns: None: if the NEP5Token instance `Name` is already set. True: if all information was retrieved. False: if information retrieval failed. """ if self.name is not None: # don't query twice return sb = ScriptBuilder() sb.EmitAppCallWithOperation(self.ScriptHash, 'name') sb.EmitAppCallWithOperation(self.ScriptHash, 'symbol') sb.EmitAppCallWithOperation(self.ScriptHash, 'decimals') engine = ApplicationEngine.Run(sb.ToArray()) results = engine.EvaluationStack.Items try: self.name = results[0].GetString() self.symbol = results[1].GetString() self.decimals = results[2].GetBigInteger() if len(self.name) > 1 and self.name != 'Stack Item' \ and len(self.symbol) > 1 and self.symbol != 'Stack Item'\ and self.decimals < 10: return True except Exception as e: logger.info("could not query token %s " % e) return False
def GetScripts(self): if not self.Completed: raise Exception("Signature Context not complete") scripts = [] for i in range(0, len(self.Parameters)): sb = ScriptBuilder() plist = list(self.Parameters[i]) plist.reverse() for p in plist: sb.push(p) witness = Witness(invocation_script=sb.ToArray(), verification_script=self.Verifications[i]) scripts.append(witness) return scripts
def get_token_balance(self, request, hash_value, address_contract): request.setHeader('Content-Type', 'application/json') try: print(address_contract) addr = parse_param(address_contract) if isinstance(addr, UInt160): addr = addr.Data sb = ScriptBuilder() sb.EmitAppCallWithOperationAndArgs(UInt160.ParseString(hash_value), 'balanceOf', [addr]) response = self.get_invoke_result_balance(sb.ToArray()) return json.dumps(response) except Exception as e: # logger.info("Could not get contract with hash %s because %s " % (contract_hash, e)) return self.format_message( "Could not get balance with hash %s because %s " % (hash_value, e)) # return self.format_notifications(request, notifications) return self.format_message( "Could not get balance with hash %s because test" % (hash_value))
def Query(self): """ Query the smart contract for its token information (name, symbol, decimals). Args: wallet (neo.Wallets.Wallet): a wallet instance. Returns: None: if the NEP5Token instance `Name` is already set. True: if all information was retrieved. False: if information retrieval failed. """ if self.name is not None: # don't query twice return sb = ScriptBuilder() sb.EmitAppCallWithOperation(self.ScriptHash, 'name') sb.EmitAppCallWithOperation(self.ScriptHash, 'symbol') sb.EmitAppCallWithOperation(self.ScriptHash, 'decimals') snapshot = GetBlockchain().Default()._db.createSnapshot().Clone() engine = None try: engine = ApplicationEngine.Run(snapshot, sb.ToArray(), exit_on_error=True, gas=Fixed8.FromDecimal(10.0), test_mode=False) except Exception as e: traceback.print_exc() pass if engine and len(engine.ResultStack.Items) == 3: results = engine.ResultStack.Items try: self.name = results[0].GetString() self.symbol = results[1].GetString() self.decimals = results[2].GetBigInteger() if len(self.name) > 1 and self.name != 'Stack Item' \ and len(self.symbol) > 1 and self.symbol != 'Stack Item' \ and self.decimals < 10: return True except Exception as e: pass return False
def TestInvokeContract(wallet, args): BC = GetBlockchain() contract = BC.GetContract(args[0]) if contract: descripe_contract(contract) verbose = False if 'verbose' in args: verbose = True args.remove('verbose') print("VERBOSE %s " % verbose) params = args[1:] if len(args) > 1 else [] if len(params) > 0 and params[0] == 'describe': return params.reverse() sb = ScriptBuilder() for p in params: item = parse_param(p) sb.push(item) sb.EmitAppCall(contract.Code.ScriptHash().Data) out = sb.ToArray() return test_invoke(out, wallet) else: print("Contract %s not found" % args[0]) return None, None
def CreateMultiSigRedeemScript(m, publicKeys): if m < 1: raise Exception( "Minimum required signature count is 1, specified {}.".format( m)) if m > len(publicKeys): raise Exception( "Invalid public key count. Minimum required signatures is bigger than supplied public keys count." ) if len(publicKeys) > 1024: raise Exception( "Supplied public key count ({}) exceeds maximum of 1024.". format(len(publicKeys))) sb = ScriptBuilder() sb.push(m) pkeys = [point for point in publicKeys] pkeys.sort() keys = [p.encode_point().decode() for p in pkeys] for key in keys: sb.push(key) sb.push(len(publicKeys)) sb.add(CHECKMULTISIG) return sb.ToArray()
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 json_rpc_method_handler(self, method, params): if method == "getaccountstate": acct = Blockchain.Default().GetAccountState(params[0]) if acct is None: try: acct = AccountState(script_hash=Helper.AddrStrToScriptHash(params[0])) except Exception as e: raise JsonRpcError(-2146233033, "One of the identified items was in an invalid format.") return acct.ToJson() elif method == "getassetstate": asset_id = UInt256.ParseString(params[0]) asset = Blockchain.Default().GetAssetState(asset_id.ToBytes()) if asset: return asset.ToJson() raise JsonRpcError(-100, "Unknown asset") elif method == "getbestblockhash": return '0x%s' % Blockchain.Default().CurrentHeaderHash.decode('utf-8') elif method == "getblock": # this should work for either str or int block = Blockchain.Default().GetBlock(params[0]) if not block: raise JsonRpcError(-100, "Unknown block") return self.get_block_output(block, params) elif method == "getblockcount": return Blockchain.Default().Height + 1 elif method == "getblockhash": height = params[0] if height >= 0 and height <= Blockchain.Default().Height: return '0x%s' % Blockchain.Default().GetBlockHash(height).decode('utf-8') else: raise JsonRpcError(-100, "Invalid Height") elif method == "getblocksysfee": height = params[0] if height >= 0 and height <= Blockchain.Default().Height: return Blockchain.Default().GetSysFeeAmountByHeight(height) else: raise JsonRpcError(-100, "Invalid Height") elif method == "getconnectioncount": return len(NodeLeader.Instance().Peers) elif method == "getcontractstate": script_hash = UInt160.ParseString(params[0]) contract = Blockchain.Default().GetContract(script_hash.ToBytes()) if contract is None: raise JsonRpcError(-100, "Unknown contract") return contract.ToJson() elif method == "getrawmempool": return list(map(lambda hash: "0x%s" % hash.decode('utf-8'), NodeLeader.Instance().MemPool.keys())) elif method == "getversion": return { "port": self.port, "nonce": NodeLeader.Instance().NodeId, "useragent": settings.VERSION_NAME } elif method == "getrawtransaction": tx_id = UInt256.ParseString(params[0]) tx, height = Blockchain.Default().GetTransaction(tx_id) if not tx: raise JsonRpcError(-100, "Unknown Transaction") return self.get_tx_output(tx, height, params) elif method == "getstorage": script_hash = UInt160.ParseString(params[0]) key = binascii.unhexlify(params[1].encode('utf-8')) storage_key = StorageKey(script_hash=script_hash, key=key) storage_item = Blockchain.Default().GetStorageItem(storage_key) if storage_item: return storage_item.Value.hex() return None elif method == "gettxout": hash = params[0].encode('utf-8') index = params[1] utxo = Blockchain.Default().GetUnspent(hash, index) if utxo: return utxo.ToJson(index) else: return None elif method == "invoke": shash = UInt160.ParseString(params[0]) contract_parameters = [ContractParameter.FromJson(p) for p in params[1]] sb = ScriptBuilder() sb.EmitAppCallWithJsonArgs(shash, contract_parameters) return self.get_invoke_result(sb.ToArray()) elif method == "invokefunction": contract_parameters = [] if len(params) > 2: contract_parameters = [ContractParameter.FromJson(p).ToVM() for p in params[2]] sb = ScriptBuilder() sb.EmitAppCallWithOperationAndArgs(UInt160.ParseString(params[0]), params[1], contract_parameters) return self.get_invoke_result(sb.ToArray()) elif method == "invokescript": script = params[0].encode('utf-8') return self.get_invoke_result(script) elif method == "sendrawtransaction": tx_script = binascii.unhexlify(params[0].encode('utf-8')) transaction = Transaction.DeserializeFromBufer(tx_script) result = NodeLeader.Instance().Relay(transaction) return result elif method == "mw_construct_send_tx": return MyWishMethods.construct_send_tx(self.wallet, params) elif method == "mw_construct_deploy_tx": return MyWishMethods.construct_deploy_tx(self.wallet, params) elif method == "mw_construct_invoke_tx": return MyWishMethods.construct_invoke_tx(self.wallet, params) elif method == "getapplicationlog": assert(all([x in '1234567890abcdefABCDEFxX' for x in params[0]])) # prevent traversal try: with open('/home/neo/neo-python/notis/' + params[0]) as f: res = [json.loads(x) for x in f.read().split('\n') if x] return [{'name': x['notify_type'], 'contract': x['contract'], 'args': x['payload']} for x in res] except FileNotFoundError: return ([]) elif method == "submitblock": raise NotImplementedError() elif method == "validateaddress": return self.validateaddress(params) elif method == "getpeers": return self.get_peers() raise JsonRpcError.methodNotFound()
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, invoke_attrs=None, owners=None): bc = GetBlockchain() 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) if settings.USE_DEBUG_STORAGE: debug_storage = DebugStorage.instance() storages = DBCollection(debug_storage.db, 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 = PromptUtils.lookup_addr_str(wallet, from_addr) try: dtx = wallet.MakeTransaction(tx=dtx, from_addr=from_addr) except (ValueError, TXFeeError): pass 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)) ] dtx.Attributes = make_unique_script_attr(dtx.Attributes) to_dispatch = [] engine = ApplicationEngine(trigger_type=TriggerType.Application, container=dtx, table=script_table, service=service, gas=dtx.Gas, testMode=True) engine.LoadScript(dtx.Script) # first we will execute the test deploy # then right after, we execute the test invoke d_success = engine.Execute() if d_success: items = engine.ResultStack.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 = PromptUtils.get_asset_attachments( invoke_args) invoke_args, no_parse_addresses = PromptUtils.get_parse_addresses( invoke_args) invoke_args.reverse() if '--i' in invoke_args: invoke_args = [] for index, iarg in enumerate(contract_state.Code.ParameterList): param, abort = PromptUtils.gather_param(index, iarg) if abort: return None, [], 0, None else: invoke_args.append(param) invoke_args.reverse() sb = ScriptBuilder() for p in invoke_args: item = PromptUtils.parse_param(p, wallet, parse_addr=no_parse_addresses) if type(item) is list: item.reverse() listlength = len(item) for listitem in item: subitem = PromptUtils.parse_param( listitem, wallet, parse_addr=no_parse_addresses) if type(subitem) is list: subitem.reverse() for listitem2 in subitem: subsub = PromptUtils.parse_param( listitem2, wallet, parse_addr=no_parse_addresses) sb.push(subsub) sb.push(len(subitem)) sb.Emit(PACK) else: 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 = deepcopy(invoke_attrs) if invoke_attrs else [] itx.Script = binascii.unhexlify(out) if len(outputs) < 1 and not owners: contract = wallet.GetDefaultContract() itx.Attributes.append( TransactionAttribute(usage=TransactionAttributeUsage.Script, data=contract.ScriptHash)) itx.Attributes = make_unique_script_attr(itx.Attributes) try: itx = wallet.MakeTransaction(tx=itx, from_addr=from_addr) except (ValueError, TXFeeError): pass context = ContractParametersContext(itx) wallet.Sign(context) if owners: owners = list(owners) for owner in owners: itx.Attributes.append( TransactionAttribute( usage=TransactionAttributeUsage.Script, data=owner)) itx.Attributes = make_unique_script_attr(itx.Attributes) context = ContractParametersContext(itx, isMultiSig=True) if context.Completed: itx.scripts = context.GetScripts() else: logger.warn( "Not gathering signatures for test build. For a non-test invoke that would occur here." ) # if not gather_signatures(context, itx, owners): # return None, [], 0, None # print("gathered signatures %s " % itx.scripts) engine = ApplicationEngine(trigger_type=TriggerType.Application, container=itx, table=script_table, service=service, gas=itx.Gas, testMode=invocation_test_mode) engine.invocation_args = invoke_args engine.LoadScript(itx.Script) engine.LoadDebugInfoForScriptHash(debug_map, shash.Data) 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: 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.ResultStack.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 TestInvokeContract(wallet, args, withdrawal_tx=None, parse_params=True, from_addr=None, min_fee=DEFAULT_MIN_FEE): BC = GetBlockchain() contract = BC.GetContract(args[0]) if contract: verbose = False if 'verbose' in args: descripe_contract(contract) verbose = True args.remove('verbose') # params = args[1:] if len(args) > 1 else [] if len(params) > 0 and params[0] == 'describe': return params, neo_to_attach, gas_to_attach = get_asset_attachments(params) params.reverse() sb = ScriptBuilder() for p in params: if parse_params: item = parse_param(p, wallet) else: item = p if type(item) is list: item.reverse() listlength = len(item) for listitem in item: sb.push(listitem) sb.push(listlength) sb.Emit(PACK) else: sb.push(item) sb.EmitAppCall(contract.Code.ScriptHash().Data) out = 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) return test_invoke(out, wallet, outputs, withdrawal_tx, from_addr, min_fee) else: print("Contract %s not found" % args[0]) return None, None, None, None
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() 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.LoadDebugInfoForScriptHash(debug_map, shash.Data) # 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 CreateSignatureRedeemScript(publicKey): sb = ScriptBuilder() sb.push(publicKey.encode_point(compressed=True)) sb.add(CHECKSIG) return sb.ToArray()
def generate_deploy_script(script, name='test', version='test', author='test', email='test', description='test', contract_properties=0, return_type=bytearray(b'\xff'), parameter_list=[]): sb = ScriptBuilder() plist = parameter_list try: plist = bytearray(binascii.unhexlify(parameter_list)) except Exception as e: pass sb.push(binascii.hexlify(description.encode('utf-8'))) sb.push(binascii.hexlify(email.encode('utf-8'))) sb.push(binascii.hexlify(author.encode('utf-8'))) sb.push(binascii.hexlify(version.encode('utf-8'))) sb.push(binascii.hexlify(name.encode('utf-8'))) sb.push(contract_properties) sb.push(return_type) sb.push(plist) sb.WriteVarData(script) sb.EmitSysCall("Neo.Contract.Create") script = sb.ToArray() return script
def CreateMultiSigRedeemScript(m, publicKeys): if m < 2 or m > len(publicKeys) or len(publicKeys) > 1024: raise Exception('Invalid keys') sb = ScriptBuilder() sb.push(m) pkeys = [point for point in publicKeys] pkeys.sort() keys = [p.encode_point().decode() for p in pkeys] for key in keys: sb.push(key) sb.push(len(publicKeys)) sb.add(CHECKMULTISIG) return sb.ToArray()
def json_rpc_method_handler(self, method, params): if method == "getaccountstate": acct = Blockchain.Default().GetAccountState(params[0]) if acct is None: try: acct = AccountState( script_hash=Helper.AddrStrToScriptHash(params[0])) except Exception as e: raise JsonRpcError( -2146233033, "One of the identified items was in an invalid format." ) return acct.ToJson() elif method == "getassetstate": asset_id = UInt256.ParseString(params[0]) asset = Blockchain.Default().GetAssetState(asset_id.ToBytes()) if asset: return asset.ToJson() raise JsonRpcError(-100, "Unknown asset") elif method == "getbestblockhash": return '0x%s' % Blockchain.Default().CurrentHeaderHash.decode( 'utf-8') elif method == "getblock": # this should work for either str or int block = Blockchain.Default().GetBlock(params[0]) if not block: raise JsonRpcError(-100, "Unknown block") return self.get_block_output(block, params) elif method == "getblockcount": return Blockchain.Default().Height + 1 elif method == "getblockhash": height = params[0] if height >= 0 and height <= Blockchain.Default().Height: return '0x%s' % Blockchain.Default().GetBlockHash( height).decode('utf-8') else: raise JsonRpcError(-100, "Invalid Height") elif method == "getblocksysfee": height = params[0] if height >= 0 and height <= Blockchain.Default().Height: return Blockchain.Default().GetSysFeeAmountByHeight(height) else: raise JsonRpcError(-100, "Invalid Height") elif method == "getconnectioncount": return len(NodeLeader.Instance().Peers) elif method == "getcontractstate": script_hash = UInt160.ParseString(params[0]) contract = Blockchain.Default().GetContract(script_hash.ToBytes()) if contract is None: raise JsonRpcError(-100, "Unknown contract") return contract.ToJson() elif method == "getrawmempool": return list( map(lambda hash: "0x%s" % hash.decode('utf-8'), NodeLeader.Instance().MemPool.keys())) elif method == "getversion": return { "port": self.port, "nonce": NodeLeader.Instance().NodeId, "useragent": settings.VERSION_NAME } elif method == "getrawtransaction": tx_id = UInt256.ParseString(params[0]) tx, height = Blockchain.Default().GetTransaction(tx_id) if not tx: raise JsonRpcError(-100, "Unknown Transaction") return self.get_tx_output(tx, height, params) elif method == "getstorage": script_hash = UInt160.ParseString(params[0]) key = binascii.unhexlify(params[1].encode('utf-8')) storage_key = StorageKey(script_hash=script_hash, key=key) storage_item = Blockchain.Default().GetStorageItem(storage_key) if storage_item: return storage_item.Value.hex() return None elif method == "gettxout": hash = params[0].encode('utf-8') index = params[1] utxo = Blockchain.Default().GetUnspent(hash, index) if utxo: return utxo.ToJson(index) else: return None elif method == "invoke": shash = UInt160.ParseString(params[0]) contract_parameters = [ ContractParameter.FromJson(p) for p in params[1] ] sb = ScriptBuilder() sb.EmitAppCallWithJsonArgs(shash, contract_parameters) return self.get_invoke_result(sb.ToArray()) elif method == "invokefunction": contract_parameters = [] if len(params) > 2: contract_parameters = [ ContractParameter.FromJson(p).ToVM() for p in params[2] ] sb = ScriptBuilder() sb.EmitAppCallWithOperationAndArgs(UInt160.ParseString(params[0]), params[1], contract_parameters) return self.get_invoke_result(sb.ToArray()) elif method == "invokescript": script = params[0].encode('utf-8') return self.get_invoke_result(script) elif method == "sendrawtransaction": tx_script = binascii.unhexlify(params[0].encode('utf-8')) transaction = Transaction.DeserializeFromBufer(tx_script) result = NodeLeader.Instance().Relay(transaction) return result elif method == "validateaddress": return self.validateaddress(params) elif method == "getpeers": return self.get_peers() elif method == "getbalance": if self.wallet: return self.get_balance(params) else: raise JsonRpcError(-400, "Access denied.") elif method == "getwalletheight": if self.wallet: return self.wallet.WalletHeight else: raise JsonRpcError(-400, "Access denied.") elif method == "listaddress": if self.wallet: return self.list_address() else: raise JsonRpcError(-400, "Access denied.") elif method == "getnewaddress": if self.wallet: keys = self.wallet.CreateKey() account = Account.get( PublicKeyHash=keys.PublicKeyHash.ToBytes()) return account.contract_set[0].Address.ToString() else: raise JsonRpcError(-400, "Access denied.") raise JsonRpcError.methodNotFound()
def generate_deploy_script(script, name='test', version='test', author='test', email='test', description='test', contract_properties=0, return_type=BigInteger(255), parameter_list=[]): sb = ScriptBuilder() plist = parameter_list try: plist = bytearray(binascii.unhexlify(parameter_list)) except Exception as e: pass sb.push(binascii.hexlify(description.encode('utf-8'))) sb.push(binascii.hexlify(email.encode('utf-8'))) sb.push(binascii.hexlify(author.encode('utf-8'))) sb.push(binascii.hexlify(version.encode('utf-8'))) sb.push(binascii.hexlify(name.encode('utf-8'))) sb.push(contract_properties) sb.push(return_type) sb.push(plist) sb.WriteVarData(script) sb.EmitSysCall("Neo.Contract.Create") script = sb.ToArray() return script