6

There are various scenarios when you may possess either account id (this is public information) or own the private (secret) key (e.g. extract it from NEAR Wallet local storage), and you want to know the corresponding public key.

What are the options to get the relevant public keys?

Vlad Frolov
  • 7,445
  • 5
  • 33
  • 52

1 Answers1

9

NEAR protocol uses EdDSA signature, and thus ed25519 keys are used. Having a private (secret) key, you can derive the corresponding public key (but you cannot derive the private key from the public key). Most of the libraries that implement EdDSA signing allows to derive a public key from a secret key, and here is how you can do that with near-api-js:

const nearApi = require('near-api-js')

// NEVER SHARE your private (secret) keys! (The key I used below is not used anywhere)
const keyPair = nearApi.KeyPair.fromString('ed25519:43qKAz3LfCTWpTAZPgA1DGsuwbiAjyosXpDrw24efAGP8Q3TcrnoUzTQHNRF5EbNTR38GRVdsHai9sRnzVu755gU')

console.log(keyPair.getPublicKey().toString())

Thus, having the secret key, you can always get the corresponding public key offline.

If you don't have a secret key, you won't be able to sign transactions, but you may still want to know the public keys that belong to some user, in which case you can query NEAR protocol network through RPC:

http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=query \
  params:='{
    "request_type": "view_access_key_list",
    "finality": "final",
    "account_id": "near.test"
  }'

or with cURL:

curl -X POST https://rpc.testnet.near.org -H 'content-type: application/json' --data \
  '{
    "jsonrpc": "2.0",
    "id": "dontcare",
    "method": "query",
    "params": {
      "request_type": "view_access_key_list",
      "finality": "final",
      "account_id": "near.test"
    }
  }'

In response you will find all the public keys with their permissions for a given (near.test) account id.

Vlad Frolov
  • 7,445
  • 5
  • 33
  • 52
  • 3
    To quickly get the public key from a known private key, you may use NEAR CLI (`npm i -g near-cli`) and run: `near repl` `nearAPI.KeyPair.fromString('ed25519:43qKAz3LfCTWpTAZPgA1DGsuwbiAjyosXpDrw24efAGP8Q3TcrnoUzTQHNRF5EbNTR38GRVdsHai9sRnzVu755gU').publicKey.toString()` (`nearAPI` is one of the available objects in [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)) – mikeDOTexe Sep 29 '20 at 21:22
  • 2
    As a helpful link, see https://near.github.io/account-lookup to look up more info about accounts, including their associated lockup contracts and balances – Erik Trautman Oct 11 '20 at 17:54
  • How to get private key programatically to broadcast TX? – Andon Mitev Jan 14 '21 at 11:41
  • @AndonMitev ask a separate question, please, with more details on your use-case including the context you run the code (browser, node.js, contract, something else?) – Vlad Frolov Jan 18 '21 at 15:29