NEO Smart Contract: Caller Validation

in #neo7 years ago (edited)

In many, if not all cases, you will probably be wanting to validate whether the address invoking your contract code is really who they say they are.

Thankfully we are provided with the following validation method:

boa.blockchain.vm.Neo.Runtime.CheckWitness


This method accepts a single parameter which represents the address that you would like to validate against the address used to invoke the contract code.

The provided input value can be in any of the following formats which can be used to identify the caller address:

#\xba\'\x03\xc52c\xe8\xd6\xe5"\xdc2 39\xdc\xd8\xee\xe9
AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y
031a6c6fbbdf02ca351745fa86b9ba5a9452d785ac4f7fc2b7548ca2a46c4fcf4a


These can all be found in the neo-python cli when running the command:

wallet



In order to test this out, we can use the following sample contract code:

from boa.blockchain.vm.Neo.Runtime import CheckWitness
def Main(caller):
   isCaller = CheckWitness(caller)
   if isCaller:
        return True
   return False


This will simply validate whether the provided input for caller matches the address that was used to invoke the contract.From our neo-python cli, we can use any of the following queries to test this out using our build & test method.Address:

build smartContracts/callerValidation.py test 07 01 False False AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y


Public key:

build smartContracts/callerValidation.py test 07 01 False False 031a6c6fbbdf02ca351745fa86b9ba5a9452d785ac4f7fc2b7548ca2a46c4fcf4a


Script hash of the address:

build smartContracts/callerValidation.py test 07 01 False False #\xba\'\x03\xc52c\xe8\xd6\xe5"\xdc2 39\xdc\xd8\xee\xe9


Running these should all result in true if you are running on the main wallet provided for the private net. If you are running your own instance or calling from another wallet simply copy the desired value from the result of the wallet command. If you run a test execution with a value that is not your wallet, the execution will return False. For example:

build smartContracts/callerValidation.py test 07 01 False False BF3nJJpJr6o664CWJKi1QRXjqeic2zRaaa


For a more in depth example please refer to the Hasty Ogre Name Service contract code.


If you found this tutorial helpful, please donate at:

NEO/GAS/NEP5 tokens: AR8rRBxgWw5siKsp1dUmfTLy6QQTjcqoqB
ETH/ERC20 tokens: 0x575970777095575fDd12d9cD3B105b41D8DD1344
NANO/XRB: xrb_3rpmim57tqbrb8hhjfzm1x5uk135yhmgqoj7j7wsufpo53e3ad5k93ggy1cd
LTC: M8nZ7FwJXSMAkAfiGmTKjbB7MWpdwsp52d
BTC: 3LcA1ztxFjghexRNWPyGXA59VFU3gF4PTz
BCH: 1LXLiF7SjWGday6gm61hzbYHKbSAMevwXo