omgnetwork / omg-js

JavaScript Library for communication with OMG network
Apache License 2.0
42 stars 15 forks source link

Ledger: expose domain separator and message hashing, or/and full helper #325

Closed nicholasmueller closed 3 years ago

nicholasmueller commented 3 years ago

Proposed ledger support will require clients to provide the domain separator and message hash so it can be verified on device.

We currently do not expose a way to hash these objects separately but would be trivial to implement here.

implementation:

export function hashTypedDataMessage (typedData) {
  const messageHash = structHash(typedData.types, typedData.primaryType, typedData.message);
  return bufferToHex(messageHash);
}

export function getDomainSeperatorHash (typedData) {
  const domainHash = structHash(typedData.types, 'EIP712Domain', typedData.domain);
  return bufferToHex(domainHash);
}

with a more fleshed out helper...

export async function ledgerSign (transporter, typedData) {
  const transport = new ETH(transporter);
  const messageHash = hashTypedDataMessage(typedData);
  const domainSeperatorHash = getDomainSeperatorHash(typedData);
  const { v: _v, r, s } = await transport.signEIP712HashedMessage(
        "44'/60'/0'/0/0",
        domainSeperatorHash,
        messageHash
  );
  let v = _v.toString(16);
  if (v.length < 2) {
    v = "0" + v;
  }
  return `0x${r}${s}${v}`;
}

client implementation:

// get hash values for client ui verification
const messageHash = OmgUtil.hashTypedDataMessage(typedData);
const domainSeperatorHash = OmgUtil.getDomainSeperatorHash(typedData);

// get signature
const transporter = await Transport.create();
const signature = await OmgUtil.ledgerSign(transporter, typedData);