def CreateKey(self, prikey=None): account = super(UserWallet, self).CreateKey(private_key=prikey) self._keys[account.PublicKeyHash.ToBytes()] = account self.OnCreateAccount(account) contract = WalletContract.CreateSignatureContract(account.PublicKey) self.AddContract(contract) return account
def ImportContractAddr(wallet, contract_hash, pubkey_script_hash): """ Args: wallet (Wallet): a UserWallet instance contract_hash (UInt160): hash of the contract to import pubkey_script_hash (UInt160): Returns: neo.SmartContract.Contract.Contract """ contract = Blockchain.Default().GetContract(contract_hash) if not contract or not pubkey_script_hash: print("Could not find contract") return 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(f"Added contract address {address} to wallet") return verification_contract
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 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 InvokeWithTokenVerificationScript(wallet, tx, token, fee=Fixed8.Zero()): wallet_tx = wallet.MakeTransaction(tx=tx, fee=fee, use_standard=True) if wallet_tx: token_contract_state = Blockchain.Default().GetContract( token.ScriptHash.ToString()) print("token contract %s " % token_contract_state) tx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=token.ScriptHash.Data) ] reedeem_script = token_contract_state.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\x00') verification_contract = Contract.Create( reedeem_script, param_list, wallet.GetDefaultContract().PublicKeyHash) context = ContractParametersContext(wallet_tx) wallet.Sign(context) context.Add(verification_contract, 0, 0) if context.Completed: wallet_tx.scripts = context.GetScripts() relayed = False # print("full wallet tx: %s " % json.dumps(wallet_tx.ToJson(), indent=4)) # toarray = Helper.ToArray(wallet_tx) # print("to arary %s " % toarray) relayed = NodeLeader.Instance().Relay(wallet_tx) if relayed: print("Relayed Tx: %s " % wallet_tx.Hash.ToString()) # if it was relayed, we save tx wallet.SaveTransaction(wallet_tx) return wallet_tx else: print("Could not relay tx %s " % wallet_tx.Hash.ToString()) else: print("Incomplete signature") else: print("Insufficient funds") return False
def GenesisBlock(): """ 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 FromJson(jsn, isMultiSig=True): try: parsed = json.loads(jsn) if parsed['type'] == 'Neo.Core.ContractTransaction': verifiable = ContractTransaction() ms = MemoryStream(binascii.unhexlify(parsed['hex'])) r = BinaryReader(ms) verifiable.DeserializeUnsigned(r) context = ContractParametersContext(verifiable, isMultiSig=isMultiSig) for key, value in parsed['items'].items(): if "0x" in key: key = key[2:] key = key.encode() parameterbytes = [] for pt in value['parameters']: if pt['type'] == 'Signature': parameterbytes.append(0) contract = Contract.Create(value['script'], parameterbytes, key) context.ContextItems[key] = ContextItem(contract) if 'signatures' in value: context.ContextItems[key].Signatures = value[ 'signatures'] return context else: raise ("Unsupported transaction type in JSON") except Exception as e: logger.error( "Failed to import ContractParametersContext from JSON: {}". format(e))
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 InvokeWithdrawTx(wallet, tx, contract_hash): # print("withdraw tx 1 %s " % json.dumps(tx.ToJson(), indent=4)) requestor_contract = wallet.GetDefaultContract() tx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=Crypto.ToScriptHash( requestor_contract.Script).Data) ] withdraw_contract_state = Blockchain.Default().GetContract( contract_hash.encode('utf-8')) withdraw_verification = None if withdraw_contract_state is not None: reedeem_script = withdraw_contract_state.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(withdraw_contract_state.Code.ParameterList) > 1: param_list = bytearray(withdraw_contract_state.Code.ParameterList) param_list[0] = 0 verification_contract = Contract.Create( reedeem_script, param_list, requestor_contract.PublicKeyHash) address = verification_contract.Address withdraw_verification = verification_contract context = ContractParametersContext(tx) wallet.Sign(context) context.Add(withdraw_verification, 0, 0) if context.Completed: tx.scripts = context.GetScripts() print("withdraw tx %s " % json.dumps(tx.ToJson(), indent=4)) wallet.SaveTransaction(tx) relayed = NodeLeader.Instance().Relay(tx) if relayed: print("Relayed Withdrawal Tx: %s " % tx.Hash.ToString()) return True else: print("Could not relay witdrawal tx %s " % tx.Hash.ToString()) else: print("Incomplete signature")
def InvokeWithTokenVerificationScript(wallet, tx, token, fee=Fixed8.Zero(), invoke_attrs=None): try: wallet_tx = wallet.MakeTransaction(tx=tx, fee=fee, use_standard=True) except ValueError: print("Insufficient funds") return False if wallet_tx: token_contract_state = Blockchain.Default().GetContract(token.ScriptHash.ToString()) print("token contract %s " % token_contract_state) tx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=token.ScriptHash.Data) ] if invoke_attrs: tx.Attributes += invoke_attrs reedeem_script = token_contract_state.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\x00') verification_contract = Contract.Create(reedeem_script, param_list, wallet.GetDefaultContract().PublicKeyHash) context = ContractParametersContext(wallet_tx) wallet.Sign(context) context.Add(verification_contract, 0, 0) if context.Completed: wallet_tx.scripts = context.GetScripts() nodemgr = NodeManager() relayed = nodemgr.relay(wallet_tx) if relayed: print("Relayed Tx: %s " % wallet_tx.Hash.ToString()) # if it was relayed, we save tx wallet.SaveTransaction(wallet_tx) return wallet_tx else: print("Could not relay tx %s " % wallet_tx.Hash.ToString()) else: print("Incomplete signature") else: print("Insufficient funds") return False
def __init__(self, public, is_mainnet): self._path = 'main123' if is_mainnet else 'test123' self.AddressVersion = 23 self._lock = RLock() self._indexedDB = Blockchain.Default() self.BuildDatabase() self._keys = {} self._contracts = self.LoadContracts() for key, contract in self._contracts.items(): print('contract ScriptHash', contract.ScriptHash) print('initializing', flush=True) kp = OnlyPublicKeyPair(public) self._keys[kp.PublicKeyHash.ToBytes()] = kp contract = WalletContract.CreateSignatureContract(kp.PublicKey) if contract.ScriptHash.ToBytes() not in self._contracts.keys(): self._contracts[contract.ScriptHash.ToBytes()] = contract sh = bytes(contract.ScriptHash.ToArray()) address, created = Address.get_or_create(ScriptHash=sh) address.IsWatchOnly = False address.save() db_contract = Contract.create(RawData=contract.ToArray(), ScriptHash=contract.ScriptHash.ToBytes(), PublicKeyHash=contract.PublicKeyHash.ToBytes(), Address=address, Account=None ) self.LoadNamedAddresses() self._watch_only = self.LoadWatchOnly() self._tokens = self.LoadNEP5Tokens() self._coins = self.LoadCoins() # self.initialize_holds() self._holds = VINHold.filter(IsComplete=False) # Handle EventHub events for SmartContract decorators @events.on(SmartContractEvent.RUNTIME_NOTIFY) def call_on_event(sc_event): # Make sure this event is for this specific smart contract self.on_notify_sc_event(sc_event) try: self._current_height = int(self.LoadStoredData('Height')) except: print('setting height to 0') self._current_height = 0 self.SaveStoredData('Height', self._current_height)
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 GetAddress(self): """ Returns the public NEO address for this KeyPair Returns: str: The private key """ contract = Contract.CreateSignatureContract(self.PublicKey) return contract.Address
def CreateKey(self, prikey=None): if prikey: private_key = prikey else: private_key = bytes(Random.get_random_bytes(32)) account = WalletKeyPair(priv_key=private_key) self._keys[account.PublicKeyHash.ToBytes()] = account self.OnCreateAccount(account) contract = WalletContract.CreateSignatureContract(account.PublicKey) self.AddContract(contract) return account
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 test_b(self): key = KeyPair(priv_key=self.pk) contract = Contract.CreateSignatureContract(key.PublicKey) self.assertEqual(binascii.unhexlify(contract.Script), self.contract_script) self.assertEqual(contract.ScriptHash.ToBytes(), self.contract_script_hash) self.assertEqual(contract.Address, self.contract_address) self.assertEqual(contract.PublicKeyHash, key.PublicKeyHash) self.assertEqual(contract.PublicKeyHash.ToBytes(), self.pubkeyhash)
def sign_context(binary_tx, private): wallet = Wallet(b'', b'0' * 32, True) wallet.CreateKey(binascii.unhexlify(private)) script_hash = WalletContract.CreateSignatureContract( list(wallet._keys.values())[0].PublicKey) wallet._contracts[script_hash.ScriptHash.ToBytes()] = script_hash tx = ContractTransaction.DeserializeFromBufer( binascii.unhexlify(binary_tx)) context = ContractParametersContext(tx, isMultiSig=False) context.ScriptHashes = [script_hash.ScriptHash] wallet.Sign(context) return [x.ToJson() for x in context.GetScripts()]
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 CreateKey(self, prikey=None): """ Create a KeyPair and store it encrypted in the database. Args: private_key (iterable_of_ints): (optional) 32 byte private key. Returns: KeyPair: a KeyPair instance. """ account = super(UserWallet, self).CreateKey(private_key=prikey) self.OnCreateAccount(account) contract = WalletContract.CreateSignatureContract(account.PublicKey) self.AddContract(contract) return account
def gather_signatures(context, itx, owners): do_exit = False print("\n\n*******************\n") print("Gather Signatures for Transaction:\n%s " % json.dumps(itx.ToJson(), indent=4)) print("Please use a client to sign the following: %s " % itx.GetHashData()) owner_index = 0 while not context.Completed and not do_exit: next_script = owners[owner_index] next_addr = scripthash_to_address(next_script.Data) try: print("\n*******************\n") owner_input = prompt('Public Key and Signature for %s> ' % next_addr) items = owner_input.split(' ') pubkey = ECDSA.decode_secp256r1(items[0]).G sig = items[1] contract = Contract.CreateSignatureContract(pubkey) if contract.Address == next_addr: context.Add(contract, 0, sig) print("Adding signature %s " % sig) owner_index += 1 else: print("Public Key does not match address %s " % next_addr) except ValueError: # expected from ECDSA if public key is invalid print(f"Invalid public key: {items[0]}") do_exit = True except EOFError: # Control-D pressed: quit do_exit = True except KeyboardInterrupt: # Control-C pressed: do nothing do_exit = True except Exception as e: print("Could not parse input %s " % e) if context.Completed: print("Signatures complete") itx.scripts = context.GetScripts() return True else: print("Could not finish signatures") return False
def __init__(self, public, is_mainnet): self._path = 'main123' if is_mainnet else 'test123' self.AddressVersion = 23 self._lock = RLock() self._indexedDB = Blockchain.Default() self.BuildDatabase() self._keys = {} self._contracts = self.LoadContracts() # for public in ['0294cd0a9e77f358f709e69d9375680b1eafe75373645192b5b251260f484577ea']: kp = OnlyPublicKeyPair(public) self._keys[kp.PublicKeyHash.ToBytes()] = kp contract = WalletContract.CreateSignatureContract(kp.PublicKey) if contract.ScriptHash.ToBytes() not in self._contracts.keys(): self._contracts[contract.ScriptHash.ToBytes()] = contract sh = bytes(contract.ScriptHash.ToArray()) address, created = Address.get_or_create(ScriptHash=sh) address.IsWatchOnly = False address.save() db_contract = Contract.create(RawData=contract.ToArray(), ScriptHash=contract.ScriptHash.ToBytes(), PublicKeyHash=contract.PublicKeyHash.ToBytes(), Address=address, Account=None ) self.LoadNamedAddresses() self._watch_only = self.LoadWatchOnly() self._tokens = self.LoadNEP5Tokens() self._coins = self.LoadCoins() self.initialize_holds() try: self._current_height = int(self.LoadStoredData('Height')) except: print('setting height to 0') self._current_height = 0 self.SaveStoredData('Height', self._current_height)
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 PerformWithdrawTx(wallet, tx, contract_hash): requestor_contract = wallet.GetDefaultContract() withdraw_contract_state = Blockchain.Default().GetContract( contract_hash.encode('utf-8')) reedeem_script = withdraw_contract_state.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(withdraw_contract_state.Code.ParameterList) > 1: param_list = bytearray(withdraw_contract_state.Code.ParameterList) param_list[0] = 0 verification_contract = Contract.Create(reedeem_script, param_list, requestor_contract.PublicKeyHash) context = ContractParametersContext(tx) context.Add(verification_contract, 0, bytearray(0)) if context.Completed: tx.scripts = context.GetScripts() print("withdraw tx %s " % json.dumps(tx.ToJson(), indent=4)) relayed = NodeLeader.Instance().Relay(tx) if relayed: # wallet.SaveTransaction(tx) # dont save this tx print("Relayed Withdrawal Tx: %s " % tx.Hash.ToString()) return tx else: print("Could not relay witdrawal tx %s " % tx.Hash.ToString()) else: print("Incomplete signature") return False
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 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) print("import contract address %s %s " % (contract_hash, pubkey)) print("pubkey script hash %s " % pubkey_script_hash) contract = Blockchain.Default().GetContract(contract_hash) if contract is not None: reedeem_script = contract.Code.Script param_list = contract.Code.ParameterList verification_contract = Contract.Create(pubkey_script_hash, param_list, reedeem_script) address = verification_contract.Address print("address %s " % address) print("contract objcet is %s " % contract) wallet.AddContract(verification_contract) print("Added contract addres %s to wallet" % address) return 'Hello'
def CheckWitnessPubkey(self, engine, pubkey): scripthash = Contract.CreateSignatureRedeemScript(pubkey) return self.CheckWitnessHash(engine, Crypto.ToScriptHash(scripthash))
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 == "getLastBlog": if len(params) > 0: height = params[0] else: height = Blockchain.Default().Height + 1 data = self.get_blog_content(height, "") return data; elif method == "getLastBlogByTag": if len(params) > 1: height = params[1] tag = params[0] elif len(params) > 0: tag = params[0] height = Blockchain.Default().Height + 1 else: raise JsonRpcError(-100, "no enough param") data = self.get_blog_content(height, tag) return data; elif method == "getLastBlogBySender": if len(params) > 1: height = params[1] sender = params[0] elif len(params) > 0: sender = params[0] height = Blockchain.Default().Height + 1 else: raise JsonRpcError(-100, "no enough param") data = self.get_blog_content(height, "", sender) return data; elif method == "getBlogContent": tx_id = UInt256.ParseString(params[0]) tx, height = Blockchain.Default().GetTransaction(tx_id) if not tx: raise JsonRpcError(-100, "Unknown Transaction") for attr in tx.Attributes: item = attr.ToJson; if item['usage'] == 240: item['content'] = binascii.a2b_hex(item['data']).decode("utf8") return item; raise JsonRpcError(-100, "no blog content") 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 == "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 == "createAddress": private_key = bytes(Random.get_random_bytes(32)) key = KeyPair(priv_key=private_key) self.wallet._keys[key.PublicKeyHash.ToBytes()] = key self.wallet.OnCreateAccount(key) contract = WalletContract.CreateSignatureContract(key.PublicKey) self.wallet.AddContract(contract) if key : result = {'privateKey': key.Export(),'address':contract.Address} return result; 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 == "sendBlog": # shash = UInt160.ParseString(params[0]) # contract_parameters = [ContractParameter.FromJson(p) for p in params[1]] # sb = ScriptBuilder() # sb.EmitAppCallWithJsonArgs(shash, contract_parameters) # script = sb.ToArray(); # tx = ContractTransaction() # tx.inputs = [] # tx.outputs = [] # attribute = TransactionAttribute(240, params[2].encode('utf-8')) # standard_contract = self.wallet.GetStandardAddress() # data = standard_contract.Data # tx.Attributes = [TransactionAttribute(usage=TransactionAttributeUsage.Script, # data=data)] # # tx.Attributes.append(attribute) # tx.Version = 1 # tx.scripts = [] # BC = GetBlockchain() # contract = BC.GetContract(params[0]) # output = TransactionOutput(AssetId=Blockchain.SystemShare().Hash, # Value=Fixed8.FromDecimal(float(1)), # script_hash=contract.Code.ScriptHash(), # ) # tx.outputs.append(output) # logger.info("output %s" % output.ToJson(0)) # tx.Script = binascii.unhexlify(script) # print("percentage %s %s" % (self.wallet.WalletHeight, Blockchain.Default().Height)) # scripthash_from = None # if not self.wallet.IsSynced: # raise JsonRpcError.invalidRequest("wallet not synced") # private_key = None # if len(params) > 3: # from_address = params[3] # if from_address is not None: # scripthash_from = lookup_addr_str(self.wallet, from_address) # if len(params) > 4: # private_key = params[4] # wallet_tx = SendBlog(self.wallet, tx, from_addr=scripthash_from, privatekey=private_key) # if wallet_tx != False: # return wallet_tx.ToJson(); # self.wallet.Rebuild() # raise JsonRpcError.invalidRequest("Field 'no enough asset") elif method == 'postblog': try: if len(params) > 3: from_address = params[3] assetId =Blockchain.SystemShare().Hash if len(params) > 4: private_key = params[4] if assetId is None: print("Asset id not found") return False contract_parameters = [ContractParameter.FromJson(p) for p in params[1]] sb = ScriptBuilder() sb.EmitAppCallWithJsonArgs(UInt160.ParseString(params[0]), contract_parameters) script = sb.ToArray(); scripthash_from = None if from_address is not None: scripthash_from = lookup_addr_str(self.wallet, from_address) # f8amount = Fixed8.TryParse(0, require_positive=True) # if f8amount is None: # print("invalid amount format") # return False # # if type(assetId) is UInt256 and f8amount.value % pow(10, 8 - Blockchain.Default().GetAssetState( # assetId.ToBytes()).Precision) != 0: # print("incorrect amount precision") # return False # fee = Fixed8.Zero() # # output = TransactionOutput(AssetId=assetId, Value=f8amount, script_hash=contract.Code.ScriptHash()) tx = InvocationTransaction() ttx = self.wallet.MakeTransaction(tx=tx, change_address=None, fee=fee, from_addr=scripthash_from) if ttx is None: print("insufficient funds") return False standard_contract = self.wallet.GetStandardAddress() if scripthash_from is not None: signer_contract = self.wallet.GetContract(scripthash_from) else: signer_contract = self.wallet.GetContract(standard_contract) if not signer_contract.IsMultiSigContract: data = scripthash_from.Data print(data) tx.Attributes = [TransactionAttribute(usage=TransactionAttributeUsage.Script, data=data),TransactionAttribute(usage=TransactionAttributeUsage.Remark1, data=from_address.encode('utf-8'))] # insert any additional user specified tx attributes tx.Attributes.append(TransactionAttribute(240, params[2].encode('utf-8'))) tx.Script = binascii.unhexlify(script) context = ContractParametersContext(tx, isMultiSig=signer_contract.IsMultiSigContract) if private_key is not None: prikey = KeyPair.PrivateKeyFromWIF(private_key) kp = KeyPair(prikey) self.wallet.Sign(context,kp) attributes = [attr.ToJson() for attr in tx.Attributes] print("attributes %s" %attributes) if context.Completed: tx.scripts = context.GetScripts() # print("will send tx: %s " % json.dumps(tx.ToJson(),indent=4)) relayed = NodeLeader.Instance().Relay(tx) if relayed: self.wallet.SaveTransaction(tx) print("Relayed Tx: %s " % tx.Hash.ToString()) return tx.ToJson() else: print("Could not relay tx %s " % tx.Hash.ToString()) else: print("Transaction initiated, but the signature is incomplete") print(json.dumps(context.ToJson(), separators=(',', ':'))) return False except Exception as e: print("could not send: %s " % e) return False 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 == "submitblock": raise NotImplementedError() elif method == "validateaddress": return self.validateaddress(params) elif method == "getpeers": raise NotImplementedError() raise JsonRpcError.methodNotFound()
def main(): parser = argparse.ArgumentParser( description= 'A utility for signing messages. Example usage: "np-sign mymessage --wallet_file path/to/my/wallet" or use an NEP2 key/passphrase like "np-sign mymessage -n"' ) parser.add_argument('message', type=str, help='The message in string format to be signed') parser.add_argument( '-w', '--wallet_file', type=str, default=None, help='If using a wallet file, the path to the wallet file') parser.add_argument( '-a', '--address', type=str, default=False, help= 'If using a wallet file with more than 1 address, the address you would like to use. Otherwise the default address will be used' ) parser.add_argument( '-n', '--nep2', action='store_true', help="Whether to use an NEP2 passhrase rather than a wallet") parser.add_argument('--wif', type=str, default=None, help='If using a wif pass in the wif') args = parser.parse_args() try: if args.wallet_file: passwd = prompt('[Wallet password]> ', is_password=True) wallet = UserWallet.Open(args.wallet_file, to_aes_key(passwd)) contract = wallet.GetDefaultContract() if args.address: addr = args.address script_hash = Helper.AddrStrToScriptHash(addr) contract = wallet.GetContract(script_hash) if contract is None: raise Exception('Address %s not found in wallet %s ' % (addr, args.wallet_file)) print("Signing With Address %s " % contract.Address) signature, pubkey = wallet.SignMessage(args.message, contract.ScriptHash) pubkey = pubkey.encode_point().decode('utf-8') signature = signature.hex() print("pubkey, sig: %s %s " % (pubkey, signature)) elif args.nep2: nep2_key = prompt('[nep2 key]> ', is_password=True) nep2_passwd = prompt("[nep2 key password]> ", is_password=True) prikey = KeyPair.PrivateKeyFromNEP2(nep2_key, nep2_passwd) keypair = KeyPair(priv_key=prikey) contract = Contract.CreateSignatureContract(keypair.PublicKey) print("Signing With Address %s " % contract.Address) signature = Crypto.Sign(args.message, prikey) pubkey = keypair.PublicKey.encode_point().decode('utf-8') signature = signature.hex() print("pubkey, sig: %s %s " % (pubkey, signature)) elif args.wif: prikey = KeyPair.PrivateKeyFromWIF(args.wif) keypair = KeyPair(priv_key=prikey) contract = Contract.CreateSignatureContract(keypair.PublicKey) print("Signing With Address %s " % contract.Address) signature = Crypto.Sign(args.message, prikey) pubkey = keypair.PublicKey.encode_point().decode('utf-8') signature = signature.hex() print("pubkey, sig: %s %s " % (pubkey, signature)) except Exception as e: print("Could not sign: %s " % e)
def GetConsensusAddress(validators): vlen = len(validators) script = Contract.CreateMultiSigRedeemScript(vlen - int((vlen - 1) / 3), validators) return Crypto.ToScriptHash(script)