all files / src/ keypair.js

92.78% Statements 90/97
86.36% Branches 38/44
96% Functions 24/25
86.79% Lines 46/53
8 statements, 10 branches Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216                                                  1× 116×       116×   116× 16×   16× 3×     13× 13×   13× 13× 13×   13× 1×     100×   98× 1×                       6× 2×                   8× 5×                   16×               2×     2×                 104× 97×     97×               2× 2×       97×                       3×       1×   1×               10×               7×       7× 7×                     1×               1×                 1×       1×                   1×       1× 1×   1×      
import {Network} from "./network";
import {sign, verify} from "./signing";
import * as base58 from "./base58";
import {StrKey} from "./strkey";
import {default as xdr} from "./generated/digitalbits-xdr_generated";
import nacl from "tweetnacl";
 
/**
 * `Keypair` represents public (and secret) keys of the account.
 *
 * Currently `Keypair` only supports ed25519 but in a future this class can be abstraction layer for other
 * public-key signature systems.
 *
 * Use more convenient methods to create `Keypair` object:
 * * `{@link Keypair.fromPublicKey}`
 * * `{@link Keypair.fromSecret}`
 * * `{@link Keypair.random}`
 *
 * @constructor
 * @param {object} keys At least one of keys must be provided.
 * @param {string} keys.type Public-key signature system name. (currently only `ed25519` keys are supported)
 * @param {Buffer} [keys.publicKey] Raw public key
 * @param {Buffer} [keys.secretKey] Raw secret key (32-byte secret seed in ed25519`)
 */
export class Keypair {
  constructor(keys) {
    Iif (keys.type != "ed25519") {
      throw new Error("Invalid keys type");
    }
 
    this.type = keys.type;
 
    if (keys.secretKey) {
      keys.secretKey = new Buffer(keys.secretKey);
 
      if (keys.secretKey.length != 32) {
        throw new Error("secretKey length is invalid");
      }
 
      let secretKeyUint8 = new Uint8Array(keys.secretKey);
      let naclKeys = nacl.sign.keyPair.fromSeed(secretKeyUint8);
 
      this._secretSeed = keys.secretKey;
      this._secretKey = new Buffer(naclKeys.secretKey);
      this._publicKey = new Buffer(naclKeys.publicKey);
 
      if (keys.publicKey && !this._publicKey.equals(new Buffer(keys.publicKey))) {
        throw new Error("secretKey does not match publicKey");
      }
    } else {
      this._publicKey = new Buffer(keys.publicKey);
 
      if (this._publicKey.length != 32) {
        throw new Error("publicKey length is invalid");
      }
    }
  }
 
  /**
   * Creates a new `Keypair` instance from secret. This can either be secret key or secret seed depending
   * on underlying public-key signature system. Currently `Keypair` only supports ed25519.
   * @param {string} secret secret key (ex. `SDAKFNYEIAORZKKCYRILFQKLLOCNPL5SWJ3YY5NM3ZH6GJSZGXHZEPQS`)
   * @returns {Keypair}
   */
  static fromSecret(secret) {
    let rawSecret = StrKey.decodeEd25519SecretSeed(secret);
    return this.fromRawEd25519Seed(rawSecret);
  }
 
  /**
   * Base58 address encoding is **DEPRECATED**! Use this method only for transition to strkey encoding.
   * @param {string} seed Base58 secret seed
   * @deprecated Use {@link Keypair.fromSecret}
   * @returns {Keypair}
   */
  static fromBase58Seed(seed) {
    let rawSeed = base58.decodeBase58Check("seed", seed);
    return this.fromRawEd25519Seed(rawSeed);
  }
 
  /**
   * Creates a new `Keypair` object from ed25519 secret key seed raw bytes.
   *
   * @param {Buffer} rawSeed Raw 32-byte ed25519 secret key seed
   * @returns {Keypair}
   */
  static fromRawEd25519Seed(rawSeed) {
    return new this({type: 'ed25519', secretKey: rawSeed});
  }
 
  /**
   * Returns `Keypair` object representing network master key.
   * @returns {Keypair}
   */
  static master() {
    Iif (Network.current() === null) {
      throw new Error("No network selected. Use `Network.use`, `Network.usePublicNetwork` or `Network.useTestNetwork` helper methods to select network.");
    }
    return this.fromRawEd25519Seed(Network.current().networkId());
  }
 
  /**
   * Creates a new `Keypair` object from public key.
   * @param {string} publicKey public key (ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`)
   * @returns {Keypair}
   */
  static fromPublicKey(publicKey) {
    publicKey = StrKey.decodeEd25519PublicKey(publicKey);
    Iif (publicKey.length !== 32) {
      throw new Error('Invalid DigitalBits public key');
    }
    return new this({type: 'ed25519', publicKey});
  }
 
  /**
   * Create a random `Keypair` object.
   * @returns {Keypair}
   */
  static random() {
    let secret = nacl.randomBytes(32);
    return this.fromRawEd25519Seed(secret);
  }
 
  xdrAccountId() {
    return new xdr.AccountId.publicKeyTypeEd25519(this._publicKey);
  }
 
  xdrPublicKey() {
    return new xdr.PublicKey.publicKeyTypeEd25519(this._publicKey);
  }
 
  /**
   * Returns raw public key
   * @returns {Buffer}
   */
  rawPublicKey() {
    return this._publicKey;
  }
 
  signatureHint() {
    let a = this.xdrAccountId().toXDR();
 
    return a.slice(a.length - 4);
  }
 
  /**
   * Returns public key associated with this `Keypair` object.
   * @returns {string}
   */
  publicKey() {
    return StrKey.encodeEd25519PublicKey(this._publicKey);
  }
 
  /**
   * Returns secret key associated with this `Keypair` object
   * @returns {string}
   */
  secret() {
    Iif (!this._secretSeed) {
      throw new Error("no secret key available");
    }
 
    Eif (this.type == 'ed25519') {
      return StrKey.encodeEd25519SecretSeed(this._secretSeed);
    }
 
    throw new Error("Invalid Keypair type");
  }
 
  /**
   * Returns raw secret key.
   * @returns {Buffer}
   */
  rawSecretKey() {
    return this._secretSeed;
  }
 
  /**
   * Returns `true` if this `Keypair` object contains secret key and can sign.
   * @returns {boolean}
   */
  canSign() {
    return !!this._secretKey;
  }
 
  /**
   * Signs data.
   * @param {Buffer} data Data to sign
   * @returns {Buffer}
   */
  sign(data) {
    Iif (!this.canSign()) {
      throw new Error("cannot sign: no secret key available");
    }
 
    return sign(data, this._secretKey);
  }
 
  /**
   * Verifies if `signature` for `data` is valid.
   * @param {Buffer} data Signed data
   * @param {Buffer} signature Signature
   * @returns {boolean}
   */
  verify(data, signature) {
    return verify(data, signature, this._publicKey);
  }
 
  signDecorated(data) {
    let signature = this.sign(data);
    let hint      = this.signatureHint();
 
    return new xdr.DecoratedSignature({hint, signature});
  }
}