def test_invocation_assetcreate_block(self): hexdata = binascii.unhexlify(self.asset_create_block) block = Helper.AsSerializableWithType(hexdata, 'neo.Core.Block.Block') self.assertEqual(block.Index, self.asset_create_index) result = Blockchain.Default().Persist(block) self.assertTrue(result) # now the asset that was created should be there assets = DBCollection(Blockchain.Default()._db, DBPrefix.ST_Asset, AssetState) newasset = assets.TryGet(self.asset_create_id) self.assertIsNotNone(newasset) self.assertEqual(newasset.AssetType, 1) self.assertEqual(newasset.Precision, 8) self.assertEqual(Crypto.ToAddress(newasset.Admin), self.asset_admin) self.assertEqual(Crypto.ToAddress(newasset.Issuer), self.asset_admin) self.assertIsInstance(newasset.AssetId, UInt256) self.assertEqual(newasset.AssetId.ToBytes(), self.asset_create_id)
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): 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 SearchAssetState(self, query): res = [] assets = DBCollection(self._db, DBPrefix.ST_Asset, AssetState) keys = assets.Keys for item in keys: asset = assets.TryGet(keyval=item) if query in asset.Name.decode('utf-8'): res.append(asset) elif query in Crypto.ToAddress(asset.Issuer): res.append(asset) elif query in Crypto.ToAddress(asset.Admin): res.append(asset) return res
def PrivateKeyFromWIF(wif): """ Get the private key from a WIF key Args: wif (str): The wif key Returns: bytes: The private key """ if wif is None or len(wif) is not 52: raise ValueError( 'Please provide a wif with a length of 52 bytes (LEN: {0:d})'. format(len(wif))) data = base58.b58decode(wif) length = len(data) if length is not 38 or data[0] is not 0x80 or data[33] is not 0x01: raise ValueError("Invalid format!") checksum = Crypto.Hash256(data[0:34])[0:4] if checksum != data[34:]: raise ValueError("Invalid WIF Checksum!") return data[1:33]
def ToJson(self): """ Convert object members to a dictionary that can be parsed as JSON. Returns: dict: """ jsn = super(RegisterTransaction, self).ToJson() asset = { 'type': self.AssetType, 'name': self.Name.decode('utf-8'), 'amount': self.Amount.value, 'precision': self.Precision if type(self.Precision) is int else self.Precision.decode('utf-8'), 'owner': self.Owner.ToString(), 'admin': Crypto.ToAddress(self.Admin) } jsn['asset'] = asset return jsn
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 Blockchain_GetAccount(self, engine): hash = UInt160(data=engine.EvaluationStack.Pop().GetByteArray()) address = Crypto.ToAddress(hash).encode('utf-8') account = self.Accounts.GetOrAdd(address, new_instance=AccountState(script_hash=hash)) engine.EvaluationStack.PushT(StackItem.FromInterface(account)) return True
def openWallet(self): """ open a Wallet. Needed for invoking contract methods """ if not os.path.exists(self.walletpath): logger.info("Wallet file not found") return else: assert self.Wallet is None aespasswd = to_aes_key(self.walletpw) self.Wallet = UserWallet.Open(self.walletpath, aespasswd) print("Opened wallet at: ", self.walletpath) self.wallet_sh = self.Wallet.GetStandardAddress() self.wallet_addr = Crypto.ToAddress(self.wallet_sh) print('Wallet Sh', self.wallet_sh) print('Wallet Addr', self.wallet_addr) self.Wallet.Rebuild() print("Wallet is syncing...") while self.Wallet.IsSynced is False: self._walletdb_loop = task.LoopingCall( self.Wallet.ProcessBlocks) self._walletdb_loop.start(1) print(self.Wallet._current_height, "/", Blockchain.Default().Height) return len(self.Wallet.GetTransactions())
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 __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 Storage_Delete(self, engine): context = engine.EvaluationStack.Pop().GetInterface() if not self.CheckStorageContext(context): return False key = engine.EvaluationStack.Pop().GetByteArray() storage_key = StorageKey(script_hash=context.ScriptHash, key=key) if len(key) == 20: keystr = Crypto.ToAddress(UInt160(data=key)) self.events_to_dispatch.append( SmartContractEvent(SmartContractEvent.STORAGE_DELETE, [keystr], context.ScriptHash, Blockchain.Default().Height + 1, engine.ScriptContainer.Hash if engine.ScriptContainer else None, test_mode=engine.testMode)) self._storages.Remove(storage_key.ToArray()) return True
def ToScriptHash(self, address): """ Retrieve the script_hash based from an address. Args: address (str): a base58 encoded address. Raises: ValuesError: if an invalid address is supplied or the coin version is incorrect Exception: if the address string does not start with 'A' or the checksum fails Returns: UInt160: script hash. """ if len(address) == 34: if address[0] == 'A': data = b58decode(address) if data[0] != self.AddressVersion: raise ValueError('Not correct Coin Version') checksum = Crypto.Default().Hash256(data[:21])[:4] if checksum != data[21:]: raise Exception('Address format error') return UInt160(data=data[1:21]) else: raise Exception('Address format error') else: raise ValueError('Not correct Address, wrong length.')
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 test_script_hash(self): # Expected output taken from running: getHash(Buffer.from('abc', 'utf8')).toString('hex') # using https://github.com/CityOfZion/neon-wallet-react-native/blob/master/app/api/crypto/index.js expected_result = b'bb1be98c142444d7a56aa3981c3942a978e4dc33' result = Crypto.Default().Hash160(b'abc') self.assertEqual(expected_result, binascii.hexlify(result))
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, trigger_type, container, table, service, gas, testMode=False, exit_on_error=False): super(ApplicationEngine, self).__init__(container=container, crypto=Crypto.Default(), table=table, service=service, exit_on_error=exit_on_error) self.Trigger = trigger_type self.gas_amount = self.gas_free + gas.value self.testMode = testMode
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 hex2address(input): try: output = Crypto.ToAddress( UInt160(data=binascii.unhexlify(bytearray(input.encode("utf8"))))) except: output = None return output
def Address(self): """ Get the public address of the transaction. Returns: str: base58 encoded string representing the address. """ return Crypto.ToAddress(self.ScriptHash)
def main(): tx = construct_tx() tx_data = get_tx_data(tx) signstr =binascii.hexlify(Crypto.Sign(message=tx_data, private_key=private_key)).decode() rawtx_data = tx_data + "014140" + signstr + "2321" + public_key + "ac" print (rawtx_data) #waiting for relay
def Address(self): """ Get the accounts public address. Returns: str: base58 encoded string representing the account address. """ return Crypto.ToAddress(self.ScriptHash)
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 address_to_scripthash(address): data = b58decode(address) if len(data) != 25: raise ValueError('Not correct Address, wrong length.') if data[0] != settings.ADDRESS_VERSION: raise ValueError('Not correct Coin Version') checksum = Crypto.Default().Hash256(data[:21])[:4] if checksum != data[21:]: raise Exception('Address format error') return UInt160(data=data[1:21]).ToBytes()
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 Address(self): """ Get the wallet address associated with the token. Returns: str: base58 encoded string representing the wallet address. """ if self._address is None: self._address = Crypto.ToAddress(self.ScriptHash) return self._address
def Storage_Get(self, engine): context = None try: item = engine.EvaluationStack.Pop() context = item.GetInterface() shash = context.ScriptHash except Exception as e: logger.error("could not get storage context %s " % e) return False contract = Blockchain.Default().GetContract( context.ScriptHash.ToBytes()) if contract is not None: if not contract.HasStorage: return False else: return False key = engine.EvaluationStack.Pop().GetByteArray() storage_key = StorageKey(script_hash=context.ScriptHash, key=key) item = Blockchain.Default().GetStorageItem(storage_key) keystr = key valStr = bytearray(0) if item is not None: valStr = bytearray(item.Value) if len(key) == 20: keystr = Crypto.ToAddress(UInt160(data=key)) try: valStr = int.from_bytes(valStr, 'little') except Exception as e: logger.error("Could not convert %s to number: %s " % (valStr, e)) if item is not None: engine.EvaluationStack.PushT(bytearray(item.Value)) else: engine.EvaluationStack.PushT(bytearray(0)) self.events_to_dispatch.append( SmartContractEvent(SmartContractEvent.STORAGE_GET, ['%s -> %s' % (keystr, valStr)], context.ScriptHash, Blockchain.Default().Height + 1, engine.ScriptContainer.Hash, test_mode=engine.testMode)) return True