Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(hw-app-trx): support #signTIP712HashedMessage() for Tron #6779

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

zorro11639
Copy link

@zorro11639 zorro11639 commented Apr 30, 2024

βœ… Checklist

  • npx changeset was attached.
  • Covered by automatic tests.
  • Impact of the changes:

πŸ“ Description

Adding the support of TIP712 Signing to hw-app-trx

πŸ“Έ Demo

var  AppTrx = require("@ledgerhq/hw-app-trx").default;
var Transport = require("@ledgerhq/hw-transport-node-hid").default;
var ethers = require("ethers")

function isHexChar(c) {
    if ((c >= 'A' && c <= 'F') ||
        (c >= 'a' && c <= 'f') ||
        (c >= '0' && c <= '9')) {
        return 1;
    }

    return 0;
}

function hexChar2byte(c) {
    let d;

    if (c >= 'A' && c <= 'F')
        d = c.charCodeAt(0) - 'A'.charCodeAt(0) + 10;
    else if (c >= 'a' && c <= 'f')
        d = c.charCodeAt(0) - 'a'.charCodeAt(0) + 10;
    else if (c >= '0' && c <= '9')
        d = c.charCodeAt(0) - '0'.charCodeAt(0);

    if (typeof d === 'number')
        return d;
    else
        throw new Error('The passed hex char is not a valid hex char');
}
function hexStr2byteArray(str, strict = false) {
    if (typeof str !== 'string')
        throw new Error('The passed string is not a string')

    let len = str.length;

    if (strict) {
        if (len % 2) {
            str = `0${str}`;
            len++;
        }
    }
    const byteArray = Array();
    let d = 0;
    let j = 0;
    let k = 0;

    for (let i = 0; i < len; i++) {
        const c = str.charAt(i);

        if (isHexChar(c)) {
            d <<= 4;
            d += hexChar2byte(c);
            j++;

            if (0 === (j % 2)) {
                byteArray[k++] = d;
                d = 0;
            }
        } else
            throw new Error('The passed hex char is not a valid hex string')
    }

    return byteArray;
}

async function verifySignature(addr, domainSeparatorHex, hashStructMessageHex, signature){
    const SIGN_MAGIC = '\x19\x01'
    domainSeparatorHex = domainSeparatorHex.replace(/^0x/, '');
    hashStructMessageHex = hashStructMessageHex.replace(/^0x/, '')
    signature = signature.replace(/^0x/, '');
    const messageBytes = [
        ...ethers.utils.toUtf8Bytes(SIGN_MAGIC),
        ...hexStr2byteArray(domainSeparatorHex),
        ...hexStr2byteArray(hashStructMessageHex)
    ];


    const messageDigest = ethers.utils.keccak256(messageBytes);

    const recovered = ethers.utils.recoverAddress(messageDigest, {
        recoveryParam: signature.substring(128, 130) == '1c' ? 1 : 0,
        r: '0x' + signature.substring(0, 64),
        s: '0x' + signature.substring(64, 128)
    });

    const tronAddress = "41" + recovered.substr(2);
    const base58Address = tronWeb.address.fromHex(tronAddress);
    return base58Address == addr;
}
async function SignTIP712MessageDemo(){
    var transport = await Transport.create();
    var tronApp = new AppTrx(transport);

    const domain = "0101010101010101010101010101010101010101010101010101010101010101"
    const struct = "0202020202020202020202020202020202020202020202020202020202020202"
    const path = "44'/195'/0'/0/0"
    const result = await tronApp.getAddress(path)
    const addr = result["address"]
    console.log("Ledger Address:" + addr)
    tronApp.signTIP712HashedMessage(path, Buffer.from(domain,"hex").toString("hex"), Buffer.from(struct, "hex").toString("hex")).then(signature => {
        console.log("Signature 0x" + signature);
        const verifyRet = verifySignature(addr, domain, struct, signature)
        console.log(verifyRet)
    })
}

@zorro11639 zorro11639 requested a review from a team as a code owner April 30, 2024 07:58
Copy link

vercel bot commented Apr 30, 2024

The latest updates on your projects. Learn more about Vercel for Git β†—οΈŽ

Name Status Preview Comments Updated (UTC)
web-tools βœ… Ready (Inspect) Visit Preview πŸ’¬ Add feedback Apr 30, 2024 8:02am
3 Ignored Deployments
Name Status Preview Comments Updated (UTC)
ledger-live-docs ⬜️ Ignored (Inspect) Visit Preview Apr 30, 2024 8:02am
native-ui-storybook ⬜️ Ignored (Inspect) Visit Preview Apr 30, 2024 8:02am
react-ui-storybook ⬜️ Ignored (Inspect) Visit Preview Apr 30, 2024 8:02am

Copy link

vercel bot commented Apr 30, 2024

@zorro11639 is attempting to deploy a commit to the LedgerHQ Team on Vercel.

A member of the Team first needs to authorize it.

@live-github-bot live-github-bot bot added ledgerjs Has changes in the ledgerjs open source libs fork Pull request base branch comes from a fork. labels Apr 30, 2024
Copy link

There as been no activity on this PR for the last 14 days. Please consider closing this PR.

@github-actions github-actions bot added the Stale label May 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
fork Pull request base branch comes from a fork. ledgerjs Has changes in the ledgerjs open source libs Stale
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant