Using @dfinity/agent in node.js

Update - @ericswanson helped me unblock this:

seed.txt

early cinnamon crucial teach mobile just toast real rebel around card priority spike aerobic result account marble hero action intact inside elbow wrestle oval

$ keysmith principal yields
bh66w-ffyze-maien-ejjje-wzhqi-crrjo-rcgs7-twjrh-kf2km-hbtia-eae

seed.js

const Identity = require("@dfinity/identity");
const hdkey = require("hdkey");
const fs = require("fs");

const { Secp256k1KeyIdentity } = Identity;

const bip39 = require("bip39");

const phrase = fs.readFileSync("seed.txt").toString().trim();

export const identityFromSeed = async (phrase) => {
  const seed = await bip39.mnemonicToSeed(phrase);
  const root = hdkey.fromMasterSeed(seed);
  const addrnode = root.derive("m/44'/223'/0'/0/0");

  return Secp256k1KeyIdentity.fromSecretKey(addrnode.privateKey);
};

identityFromSeed(phrase).then((identity) => {
  console.log(identity.getPrincipal().toString());
});

$ node seed.js yields
bh66w-ffyze-maien-ejjje-wzhqi-crrjo-rcgs7-twjrh-kf2km-hbtia-eae

We still have to hunt down the implementation used by rust-openssl/pkey.rs at master · sfackler/rust-openssl · GitHub, but this should open up the possibility to use a single identity across JS and dfx, from a shared seed phrase!

Of course, this comes with some security caveats -

  • Do not ever commit a seed phrase to your souce code.
  • THIS PATTERN SHOULD NEVER BE USED IN A FRONTEND APPLICATION
  • Use a different identity for each project to mitigate risk
  • Dfinity does not officially endorse doing this
7 Likes