涉及ecrecover、keccak256、abi.encodePacked的智能合约交易签名问题

时间:2021-03-10 21:28:01

标签: ethereum solidity smartcontracts web3

我正在尝试在本地智能合约(在 ganache 上运行)上调用以下方法,它是 Rarible 智能合约的副本,0xd07dc4262BCDbf85190C01c996b4C06a461d2430 并且在散列时遇到了一些问题。

function mint(uint256 id, uint8 v, bytes32 r, bytes32 s, Fee[] memory fees, uint256 supply, string memory uri) public {
        require(isSigner(ecrecover(keccak256(abi.encodePacked(this, id)), v, r, s)), "signer should sign tokenId");
        _mint(id, fees, supply, uri);
    }

相关python代码:

from eth_account.messages import encode_intended_validator

def to_32byte_hex(val):
    return w3.toHex(Web3.toBytes(val).rjust(32, b'\0'))

local_contract_address = "0x5a965a6aC0769ca1077b4a3C902709c4b50ea302"
item_number = 777777777

message = encode_intended_validator(w3.toChecksumAddress(local_contract_address), item_number)
signed_msg = w3.eth.account.sign_message(message,private_key=privateKey)
msg = signed_msg.messageHash
v = signed_msg['v']
r = to_32byte_hex(signed_msg['r'])
s = to_32byte_hex(signed_msg['s'])

options = {'gas':50000}
mint = contract.get_function_by_name('mint')
transaction = mint(777777777,v,r,s,[],10,'a').buildTransaction(options)

etc...

输出:

使用 hacky to_32byte_hex 函数时,参数是有效的,但我绝对没有跳过 ecrecover 函数中的 mint 步骤。

我不知道如何解决这个问题。我尝试将合同地址和 item_number 散列在一起,然后签名。我假设 v, r, s 是消息签名过程的输出,并且被签名的消息是 local_contract_addressitem_number 串联的散列。

如果答案不明显,您会推荐任何资源吗?

ValueError: {'message': 'VM Exception while processing transaction: revert signer should sign tokenId'

1 个答案:

答案 0 :(得分:0)

我找到了通过使用“ethereumjs-util”来解决这个问题的另一种方法

const util = require('ethereumjs-util');
// ...

const hash = web3.utils.soliditySha3(
  '0xE5df7fD6756bb8ffD1Cb95e8e3E7f81D9a3b56A2', // contract address
  TOKEN_ID
);
const privateKey = Buffer.from(SIGNER_PRIVATE_KEY, 'hex');
const signature = util.ecsign(util.toBuffer(hash), privateKey);
const v = signature.v;
const r = util.bufferToHex(signature.r);
const s = util.bufferToHex(signature.s);

await raribleToken.mint(
  TOKEN_ID,
  v,
  r,
  s,
  [{ recipient: user1, value: ROYALTY }],
  SUPPLY,
  URI,
  {
    from: user1,
  }
);