buffer#Buffer JavaScript Examples

The following examples show how to use buffer#Buffer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: util.js    From lx-music-mobile with Apache License 2.0 7 votes vote down vote up
decodeLyric = str => new Promise((resolve, reject) => {
  if (!str.length) return
  const buf_str = Buffer.from(str, 'base64').slice(4)
  for (let i = 0, len = buf_str.length; i < len; i++) {
    buf_str[i] = buf_str[i] ^ enc_key[i % 16]
  }
  const result = pako.inflate(buf_str, { to: 'string' })
  resolve(result)
  // (err, result) => {
  //   if (err) return reject(err)
  //   resolve(result.toString())
  // }
})
Example #2
Source File: index.js    From exchain-javascript-sdk with Apache License 2.0 6 votes vote down vote up
encodePubKeyToCompressedBuffer = pubKey => {
  let prefix = 2
  if(pubKey.y.isOdd()){
    prefix = 3
  }

  let pubBytes = Buffer.concat([
    Buffer.alloc(1, prefix),
    pubKey.x.toArrayLike(Buffer, "be", 32)
  ])
  return pubBytes
}
Example #3
Source File: v1.js    From xmrig-workers with GNU General Public License v3.0 6 votes vote down vote up
function serialize(str = true) {
  const settings = getSettings();
  const workers  = (JSON.parse(localStorage.getItem(STORAGE_KEY)) || []).map(worker => ([
    worker[0].replace('http://', ''),
    worker[1],
    worker[2],
    worker[3]
  ]));

  const array = [1, [ settings.interval ], workers];

  if (str === true) {
    return bs58.encode(Buffer.from(JSON.stringify(array)));
  }

  return array;
}
Example #4
Source File: Share.js    From pandoa with GNU General Public License v3.0 6 votes vote down vote up
function Share({ children, positions }) {
  let [selectedImage, setSelectedImage] = React.useState(null);

  let openShareDialogAsync = async () => {
    if (!(await Sharing.isAvailableAsync())) {
      alert(`Uh oh, sharing isn't available on your platform`);
      return;
    }

    //const jsonData = base64.encode(JSON.stringify(positions));
    const jsonData = Buffer.from(JSON.stringify(positions)).toString("base64");
    const url = "data:application/json;base64," + jsonData;

    //console.log("url", url);

    await FileSystem.writeAsStringAsync(
      FileSystem.documentDirectory + "pandeo-export.json",
      JSON.stringify(positions)
    );

    Sharing.shareAsync(FileSystem.documentDirectory + "pandeo-export.json", {
      message: "pandeo-export.json",
      type: "application/json",
      title: "Gread"
    });
  };

  //Alert.alert("File saved", "All points saved on your local filesystem");

  return (
    <TouchableOpacity onPress={openShareDialogAsync} style={styles.button}>
      {children}
    </TouchableOpacity>
  );
}
Example #5
Source File: testMultisigWithTwoCards.js    From sdk-samples with Apache License 2.0 6 votes vote down vote up
async sign(message, outputEncoding) {
        console.log('>>> Prepare msg for signing')
        Toast.show('>>> Prepare msg for signing')
        let msgBytes = decodeMessage(message)
        console.log('>>> msgBytes = ')
        console.log(msgBytes)
        let dataForSigning = msgBytes.toString('hex')
        console.log('>>> dataForSigning in hex = ' + dataForSigning)
        Toast.show('>>> dataForSigning in hex = ' + dataForSigning)

        const card = NativeModules.NfcCardModule
        console.log('>>> Before signature request ')
        alert("Hold the card#1 near you smartphone/iPhone. And wait about ~ 20 sec to get signature. \n Be sure the card is near your phone until you will see the key!")
        return new Promise(function (res, err) {
            setTimeout(async function () {
                console.log('>>> Start signature requesting from the card')
                const result = await card.verifyPinAndSignForDefaultHdPath(dataForSigning, "5555")
                console.log('>>> Raw signature from card =  ' + result)
                const finalRes = encodeOutput(Buffer.from(result, 'hex'), outputEncoding)
                console.log('>>> Signature in required encoding =  ' + finalRes)
                alert('Signing box got Signature from security card #1 = ' + finalRes  + ". Please remove security card#1 for now. \n  And please wait!")
                await new Promise(r => setTimeout(r, 5000))
                res(finalRes)
            }, 20000)
        })
    }
Example #6
Source File: index.js    From fcl-js with Apache License 2.0 6 votes vote down vote up
/** Transform anything into a Buffer */
export function toBuffer(v) {
  if (!Buffer.isBuffer(v)) {
    if (typeof v === "string") {
      if (isHexPrefixed(v)) {
        return Buffer.from(padToEven(stripHexPrefix(v)), "hex")
      } else {
        return Buffer.from(v)
      }
    } else if (typeof v === "number") {
      if (!v) {
        return Buffer.from([])
      } else {
        return intToBuffer(v)
      }
    } else if (v === null || v === undefined) {
      return Buffer.from([])
    } else if (v instanceof Uint8Array) {
      return Buffer.from(v)
    } else {
      throw new Error("invalid type")
    }
  }
  return v
}
Example #7
Source File: index.js    From exchain-javascript-sdk with Apache License 2.0 6 votes vote down vote up
getPrivateKeyFromKeyStore = (keystore, password) => {

  if (!_.isString(password)) {
    throw new Error("invalid password")
  }

  const json = _.isObject(keystore) ? keystore : JSON.parse(keystore)
  const kdfparams = json.crypto.kdfparams
  const options = {
    N: kdfparams.n,
    r: kdfparams.r,
    p: kdfparams.p,
    maxmem: 1024*1024*1024*2,
  }
  const derivedKey = sync(Buffer.from(password),Buffer.from(kdfparams.salt, "hex"),kdfparams.dklen,options)
  const ciphertext = Buffer.from(json.crypto.ciphertext, "hex")
  const bufferValue = Buffer.concat([derivedKey.slice(16, 32), ciphertext])
  const mac = sha256(bufferValue.toString("hex"))

  if (mac !== json.crypto.mac) {
    throw new Error("invalid password")
  }
  const decipher = cryp.createDecipheriv(json.crypto.cipher, derivedKey.slice(0, 16), Buffer.from(json.crypto.cipherparams.iv, "hex"))
  const privateKey = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("hex")

  return privateKey
}
Example #8
Source File: util.js    From lx-music-mobile with Apache License 2.0 6 votes vote down vote up
enc_key = Buffer.from([0x40, 0x47, 0x61, 0x77, 0x5e, 0x32, 0x74, 0x47, 0x51, 0x36, 0x31, 0x2d, 0xce, 0xd2, 0x6e, 0x69], 'binary')
Example #9
Source File: registry.js    From lacchain-did-js with Apache License 2.0 6 votes vote down vote up
async changeControllerSigned( address, controllerPrivateKey, newController ) {
		const nonce = await this.registry.nonce( newController );
		const sig = await signData(
			address,
			controllerPrivateKey,
			Buffer.from( "changeController" ).toString( "hex" ) +
			stripHexPrefix( newController ),
			nonce.toNumber(),
			this.conf.registry
		);
		return await this.registry.changeControllerSigned(
			address,
			sig.v,
			sig.r,
			sig.s,
			newController,
			{
				gasLimit: 1000000,
				gasPrice: 0
			}
		);
	}
Example #10
Source File: source-map-support.js    From playwright-test with MIT License 6 votes vote down vote up
retrieveMapHandlers.push((source) => {
  let sourceMappingURL = retrieveSourceMapURL(source)

  if (!sourceMappingURL) {
    return null
  }

  // Read the contents of the source map
  let sourceMapData

  if (reSourceMap.test(sourceMappingURL)) {
    // Support source map URL as a data url
    const rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1)

    sourceMapData = Buffer.from(rawData, 'base64').toString()
    sourceMappingURL = source
  } else {
    // Support source map URLs relative to the source URL
    sourceMappingURL = supportRelativeURL(source, sourceMappingURL, true)
    sourceMapData = retrieveFile(sourceMappingURL)
  }

  if (!sourceMapData) {
    return null
  }

  return {
    url: sourceMappingURL,
    map: sourceMapData,
  }
})
Example #11
Source File: crcjam.js    From SatanicaXZ with GNU General Public License v3.0 6 votes vote down vote up
crcjam = defineCrc('jam', function(buf, previous = -1) {
  if (!Buffer.isBuffer(buf)) buf = createBuffer(buf);

  let crc = previous === 0 ? 0 : ~~previous;

  for (let index = 0; index < buf.length; index++) {
    const byte = buf[index];
    crc = TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
  }

  return crc;
})
Example #12
Source File: JSONFormatter.jsx    From BinaryJsonFormatter with MIT License 6 votes vote down vote up
formatJSON(input) {
    if (input) {
      var jsonString = "";
      if (!input.startsWith("0x")) {
        input = input.replace(/\r?\n|\r/g, "");
        // check whether the input is a base64 string and then try use snappy to decompress it
        var base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
        if (base64regex.test(input)) {
          var uncompressed = SnappyJS.uncompress(Buffer.from(input, 'base64'));
          let utf8decoder = new TextDecoder()
          jsonString = utf8decoder.decode(uncompressed);
        }
        else {
          throw new Error("input needs to be a Hex String starts with '0x' or valid base64 string.");
        }
      }
      else {
        input = input.substring(2);
        var hex = Buffer.from(input, 'hex');
        if (input.toLowerCase().startsWith("1f8b")) {
          // gzip string, need to unzip first
          hex = zlib.gunzipSync(hex);
        }
        jsonString = hex.toString('utf-8');
      }

      var parsedData = JSON.parse(jsonString);
      var outputText = JSON.stringify(parsedData, null, 4);
      return outputText;
    }
    else {
      return '';
    }
  }
Example #13
Source File: crc16modbus.js    From SatanicaXZ with GNU General Public License v3.0 6 votes vote down vote up
crc16modbus = defineCrc('crc-16-modbus', function(buf, previous) {
  if (!Buffer.isBuffer(buf)) buf = createBuffer(buf);

  let crc = typeof previous !== 'undefined' ? ~~previous : 0xffff;

  for (let index = 0; index < buf.length; index++) {
    const byte = buf[index];
    crc = (TABLE[(crc ^ byte) & 0xff] ^ (crc >> 8)) & 0xffff;
  }

  return crc;
})
Example #14
Source File: kleros-escrow.js    From proof-of-humanity-web with MIT License 6 votes vote down vote up
upload(fileName, bufferOrJSON) {
    if (typeof bufferOrJSON !== "string" && !Buffer.isBuffer(bufferOrJSON))
      bufferOrJSON = JSON.stringify(bufferOrJSON);

    return fetch(`${process.env.NEXT_PUBLIC_IPFS_GATEWAY}/add`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        fileName,
        buffer: Buffer.from(bufferOrJSON),
      }),
    })
      .then((res) => res.json())
      .then(({ data }) => `/ipfs/${data[1].hash}${data[0].path}`);
  }
Example #15
Source File: testMultisigWithTwoCards.js    From sdk-samples with Apache License 2.0 5 votes vote down vote up
global.Buffer = Buffer;
Example #16
Source File: BTCSegwit.js    From RRWallet with MIT License 5 votes vote down vote up
function BTCSegwitP2SHP2WPKHAddress(pub, network) {
  const redeem = BTCSegwitP2SHRedeemScript(pub);
  const hash160 = crypto.hash160(redeem, { asByte: true }).toString();
  const version = network == NETWORK_ENV_MAINNET ? BTC_VERSION_PREFIX_SH_MAINNET : BTC_VERSION_PREFIX_SH_TESTNET;
  const checksum = hash256(`${version}${hash160}`).substr(0, CHECKSUM_HEX_LENGTH);
  const address = base58.encode(new Buffer(`${version}${hash160}${checksum}`, "hex")).toString("hex");
  return address;
}
Example #17
Source File: recoveryRegistration.js    From sdk-samples with Apache License 2.0 5 votes vote down vote up
global.Buffer = Buffer;
Example #18
Source File: index.js    From fcl-js with Apache License 2.0 5 votes vote down vote up
/** Transform an integer into a Buffer */
function intToBuffer(integer) {
  var hex = intToHex(integer)
  return Buffer.from(hex, "hex")
}
Example #19
Source File: index.js    From JsWalletDesktop with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
sha256 = payload => Buffer.from(sha('sha256').update(payload).digest())
Example #20
Source File: index.js    From exchain-javascript-sdk with Apache License 2.0 5 votes vote down vote up
generateKeyStore = (privateKeyHex, password) => {
  const salt = cryp.randomBytes(32)
  const iv = cryp.randomBytes(16)
  const cipherAlg = "aes-128-ctr"

  const kdf = "scrypt"
  const kdfparams = {
    dklen: 32,
    salt: salt.toString("hex"),
    n: 262144,
    p: 1,
    r: 8,
    //prf: "hmac-sha256"
  }
  const options = {
    N: kdfparams.n,
    r: kdfparams.r,
    p: kdfparams.p,
    maxmem: 1024*1024*1024*2,
  }

  const derivedKey = sync(Buffer.from(password),salt,kdfparams.dklen,options)
  const cipher = cryp.createCipheriv(cipherAlg, derivedKey.slice(0, 16), iv)
  if (!cipher) {
    throw new Error("createCipheriv has been failed")
  }

  const ciphertext = Buffer.concat([cipher.update(Buffer.from(privateKeyHex.toLowerCase(), "hex")), cipher.final()])
  const bufferValue = Buffer.concat([derivedKey.slice(16, 32), Buffer.from(ciphertext, "hex")])
  return {
    crypto: {
      ciphertext: ciphertext.toString("hex"),
      cipherparams: {
        iv: iv.toString("hex")
      },
      cipher: cipherAlg,
      kdf,
      kdfparams: kdfparams,
      mac: sha256(bufferValue.toString("hex"))
    },
    id: uuid.v4({
      random: cryp.randomBytes(16)
    }),
    version: 3,
  }
}
Example #21
Source File: create_buffer.js    From SatanicaXZ with GNU General Public License v3.0 5 votes vote down vote up
createBuffer =
  Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow
    ? Buffer.from
    : // support for Node < 5.10
      val => new Buffer(val)
Example #22
Source File: index.js    From lamden-js with MIT License 5 votes vote down vote up
globalThis.Buffer = Buffer;
Example #23
Source File: index.js    From exchain-javascript-sdk with Apache License 2.0 5 votes vote down vote up
generatePrivateKey = (len = 32) => Buffer.from(csprng(len)).toString("hex")
Example #24
Source File: archon-provider.js    From proof-of-humanity-web with MIT License 4 votes vote down vote up
// Only allow numbers and aplhanumeric.

export default function ArchonProvider({ children }) {
  const { web3 } = useWeb3();
  const [archon] = useState(
    () =>
      new Archon(
        web3.currentProvider,
        `${process.env.NEXT_PUBLIC_IPFS_GATEWAY}`
      )
  );
  useEffect(() => {
    if (web3.currentProvider !== archon.arbitrable.web3.currentProvider)
      archon.setProvider(web3.currentProvider);
  }, [web3.currentProvider, archon]);

  return (
    <Context.Provider
      value={useMemo(
        () => ({
          archon,
          upload(fileName, buffer) {
            return fetch(`${process.env.NEXT_PUBLIC_IPFS_GATEWAY}/add`, {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                fileName: sanitize(fileName),
                buffer: Buffer.from(buffer),
              }),
            })
              .then((res) => res.json())
              .then(
                ({ data }) =>
                  new URL(
                    `${process.env.NEXT_PUBLIC_IPFS_GATEWAY}/ipfs/${data[1].hash}${data[0].path}`
                  )
              );
          },
          uploadWithProgress(fileName, buffer, { onProgress = () => {} } = {}) {
            const xhr = new XMLHttpRequest();

            let loadListener;
            let errorListener;

            const responsePromise = new Promise((resolve, reject) => {
              xhr.open("POST", `${process.env.NEXT_PUBLIC_IPFS_GATEWAY}/add`);
              xhr.setRequestHeader("Content-Type", "application/json");

              loadListener = () => {
                resolve(xhr.response);
              };

              errorListener = () => {
                const err = new Error("Failed to submit the request");
                err.status = xhr.status;
                reject(err);
              };

              xhr.addEventListener("load", loadListener);
              xhr.addEventListener("error", errorListener);
            });

            xhr.upload.addEventListener("progress", onProgress);

            xhr.send(
              JSON.stringify({
                fileName,
                buffer: Buffer.from(buffer),
              })
            );

            const promise = Promise.resolve().then(() =>
              responsePromise
                .then((res) => JSON.parse(res))
                .then(
                  ({ data }) =>
                    new URL(
                      `${process.env.NEXT_PUBLIC_IPFS_GATEWAY}/ipfs/${data[1].hash}${data[0].path}`
                    )
                )
            );

            promise.then(() => {
              xhr.removeEventListener("load", loadListener);
              xhr.removeEventListener("error", errorListener);
              xhr.upload.removeEventListener("progress", onProgress);
            });

            return promise;
          },
        }),
        [archon]
      )}
    >
      {children}
    </Context.Provider>
  );
}
Example #25
Source File: test-basics.js    From ipfs-action with MIT License 4 votes vote down vote up
describe('dag-cbor', () => {
  const obj = {
    someKey: 'someValue',
    link: CID.parse('QmRgutAxd8t7oGkSm4wmeuByG6M51wcTso6cubDdQtuEfL'),
    links: [
      CID.parse('QmRgutAxd8t7oGkSm4wmeuByG6M51wcTso6cubDdQtuEfL'),
      CID.parse('QmRgutAxd8t7oGkSm4wmeuByG6M51wcTso6cubDdQtuEfL')
    ],
    nested: {
      hello: 'world',
      link: CID.parse('QmRgutAxd8t7oGkSm4wmeuByG6M51wcTso6cubDdQtuEfL')
    },
    bytes: new TextEncoder().encode('asdf')
  };
  const serializedObj = encode(obj);
  test('.serialize and .deserialize', () => {
    same(bytes.isBinary(serializedObj), true);
    same(bytes.toHex(serializedObj).match(/d82a/g).length, 4);
    const deserializedObj = decode(serializedObj);
    same(deserializedObj, obj);
  });
  test('.serialize and .deserialize large objects', () => {
    const dataSize = 128 * 1024;
    const largeObj = { someKey: [].slice.call(new Uint8Array(dataSize)) };
    const serialized = encode(largeObj);
    same(bytes.isBinary(serialized), true);
    const deserialized = decode(serialized);
    same(largeObj, deserialized);
  });
  test('.serialize and .deserialize object with slash as property', () => {
    const slashObject = { '/': true };
    const serialized = encode(slashObject);
    const deserialized = decode(serialized);
    same(deserialized, slashObject);
  });
  test('CIDs have clean for deep comparison', () => {
    const deserializedObj = decode(serializedObj);
    const actual = deserializedObj.link.bytes.join(',');
    const expected = obj.link.bytes.join(',');
    same(actual, expected);
  });
  test('error on circular references', () => {
    const circularObj = {};
    circularObj.a = circularObj;
    assert.throws(() => encode(circularObj), /object contains circular references/);
    const circularArr = [circularObj];
    circularObj.a = circularArr;
    assert.throws(() => encode(circularArr), /object contains circular references/);
  });
  test('error on encoding undefined', () => {
    assert.throws(() => encode(undefined), /\Wundefined\W.*not supported/);
    const objWithUndefined = {
      a: 'a',
      b: undefined
    };
    assert.throws(() => encode(objWithUndefined), /\Wundefined\W.*not supported/);
  });
  test('error on encoding IEEE 754 specials', () => {
    for (const special of [
        NaN,
        Infinity,
        -Infinity
      ]) {
      assert.throws(() => encode(special), new RegExp(`\\W${ String(special) }\\W.*not supported`));
      const objWithSpecial = {
        a: 'a',
        b: special
      };
      assert.throws(() => encode(objWithSpecial), new RegExp(`\\W${ String(special) }\\W.*not supported`));
      const arrWithSpecial = [
        1,
        1.1,
        -1,
        -1.1,
        Number.MAX_SAFE_INTEGER,
        special,
        Number.MIN_SAFE_INTEGER
      ];
      assert.throws(() => encode(arrWithSpecial), new RegExp(`\\W${ String(special) }\\W.*not supported`));
    }
  });
  test('error on decoding IEEE 754 specials', () => {
    const cases = [
      [
        'NaN',
        'f97e00'
      ],
      [
        'NaN',
        'f97ff8'
      ],
      [
        'NaN',
        'fa7ff80000'
      ],
      [
        'NaN',
        'fb7ff8000000000000'
      ],
      [
        'NaN',
        'a2616161616162fb7ff8000000000000'
      ],
      [
        'NaN',
        '8701fb3ff199999999999a20fbbff199999999999a1b001ffffffffffffffb7ff80000000000003b001ffffffffffffe'
      ],
      [
        'Infinity',
        'f97c00'
      ],
      [
        'Infinity',
        'fb7ff0000000000000'
      ],
      [
        'Infinity',
        'a2616161616162fb7ff0000000000000'
      ],
      [
        'Infinity',
        '8701fb3ff199999999999a20fbbff199999999999a1b001ffffffffffffffb7ff00000000000003b001ffffffffffffe'
      ],
      [
        '-Infinity',
        'f9fc00'
      ],
      [
        '-Infinity',
        'fbfff0000000000000'
      ],
      [
        '-Infinity',
        'a2616161616162fbfff0000000000000'
      ],
      [
        '-Infinity',
        '8701fb3ff199999999999a20fbbff199999999999a1b001ffffffffffffffbfff00000000000003b001ffffffffffffe'
      ]
    ];
    for (const [typ, hex] of cases) {
      const byts = bytes.fromHex(hex);
      assert.throws(() => decode(byts), new RegExp(`\\W${ typ.replace(/^-/, '') }\\W.*not supported`));
    }
  });
  test('fuzz serialize and deserialize with garbage', function () {
    this.timeout(5000);
    for (let ii = 0; ii < 1000; ii++) {
      const original = garbage(100);
      const encoded = encode(original);
      const decoded = decode(encoded);
      same(decoded, original);
    }
  });
  test('CIDv1', () => {
    const link = CID.parse('zdj7Wd8AMwqnhJGQCbFxBVodGSBG84TM7Hs1rcJuQMwTyfEDS');
    const encoded = encode({ link });
    const decoded = decode(encoded);
    same(decoded, { link });
  });
  test('encode and decode consistency with Uint8Array and Buffer fields', () => {
    const buffer = Buffer.from('some data');
    const bytes = Uint8Array.from(buffer);
    const s1 = encode({ data: buffer });
    const s2 = encode({ data: bytes });
    same(s1, s2);
    const verify = s => {
      same(typeof s, 'object');
      same(Object.keys(s), ['data']);
      assert(s.data instanceof Uint8Array);
      same(s.data.buffer, bytes.buffer);
    };
    verify(decode(s1));
    verify(decode(s2));
  });
  test('reject extraneous, but valid CBOR data after initial top-level object', () => {
    assert.throws(() => {
      const big = new Uint8Array(serializedObj.length + 1);
      big.set(serializedObj, 0);
      decode(big);
    }, /too many terminals/);
  });
  test('reject bad CID lead-in', () => {
    const encoded = bytes.fromHex('a1646c696e6bd82a582501017012207252523e6591fb8fe553d67ff55a86f84044b46a3e4176e10c58fa529a4aabd5');
    assert.throws(() => decode(encoded), /Invalid CID for CBOR tag 42; expected leading 0x00/);
  });
  test('sloppy decode: coerce undefined', () => {
    let encoded = bytes.fromHex('f7');
    let decoded = decode(encoded);
    same(null, decoded);
    encoded = bytes.fromHex('a26362617af763666f6f63626172');
    decoded = decode(encoded);
    same({
      foo: 'bar',
      baz: null
    }, decoded);
  });
});
Example #26
Source File: loadNote.js    From locked.fyi with MIT License 4 votes vote down vote up
LoadNote = (space) => {
  /**
   * Saves a note as a new item
   * @param {*} note
   * @param {*} stateCallback
   */
  const saveNewItem = async (thread, note, stateCallback = () => {}) => {
    stateCallback(null, states.SAVING_NEW_ITEM)
    const newNote = {
      ...note,
    }
    newNote.attributes.id = (await space.private.get("nextNoteId")) || 1
    await thread.post(buildContent(newNote))
    await space.private.set("nextNoteId", newNote.attributes.id + 1) // update the nextNoteId
    return getItemInThread(thread, newNote.attributes.id)
  }

  /**
   * saves a note as an item (replaces old version)
   * @param {*} item
   * @param {*} note
   * @param {*} stateCallback
   */
  const saveItem = async (item, thread, note, stateCallback = () => {}) => {
    stateCallback(null, states.SAVING_ITEM)
    if (!item.postId) {
      return saveNewItem(thread, note, stateCallback)
    }
    await thread.deletePost(item.postId)
    await thread.post(buildContent(note))
    return getItemInThread(thread, note.attributes.id)
  }

  /**
   * destroys an item
   * @param {*} item
   * @param {*} stateCallback
   */
  const destroyItem = async (item, thread, stateCallback = () => {}) => {
    stateCallback(null, states.DESTROYING_ITEM)
    await thread.deletePost(item.postId)
    return null
  }

  /**
   * Saves a file to IPFS and return its URL
   * @param {*} file
   */
  const addFile = async (file, stateCallback = () => {}) => {
    stateCallback(null, states.SAVING_FILE)
    const ipfs = await Box.getIPFS()
    // for some reason this does not seem to work?
    // eslint-disable-next-line no-param-reassign
    file.content = Buffer.from(await file.arrayBuffer())
    const source = await ipfs.add(file, {
      progress: (prog) => console.log(`received: ${prog}`),
    })

    return `https://ipfs.io/ipfs/${source[0].hash}`
  }

  /**
   * Retrieves a note and sets the values used in other methods
   */
  const getItem = async (
    address,
    threadId,
    noteId,
    stateCallback = () => {}
  ) => {
    let thread
    let item
    let itemThread

    // If there is a threadId and a noteId, we need to open that one
    if (threadId && noteId) {
      stateCallback(null, states.OPENING_THREAD)
      thread = await openThread(space, threadId)
      itemThread = threadId
    } else {
      // If there is no note to open, let's find which thread has space.
      // starting with the highest one.
      // It's important to start with the highest to make sure we keep the notes sorted.
      stateCallback(null, states.OPENING_THREAD)
      const nextThread = await openEarliestThreadWithSpace(
        space,
        threadId || (await space.public.get("latestThread")) || FIRST_THREAD
      )
      thread = nextThread.thread
      itemThread = nextThread.threadId
      // Save the actual thread id for faster lookup in the future!
      await space.public.set("latestThread", itemThread)
    }

    if (noteId) {
      stateCallback(null, states.RETRIEVING_ITEM)
      item = await getItemInThread(thread, noteId)
    }

    if (!item) {
      // This item does not exist or could not be found
      item = {
        message: buildContent(createNewNote(address, -1)), // use id -1 for new notes!
      }
    }
    return { item, thread, itemThread }
  }

  return {
    getItem,
    saveItem,
    destroyItem,
    addFile,
  }
}
Example #27
Source File: recoveryRegistration.js    From sdk-samples with Apache License 2.0 4 votes vote down vote up
recoveryRegistration = async (email) => {
  try {
        console.log('email = ' + email)
        console.log("Getting public key from security card")
        Toast.show("Getting public key from security card")
        alert("Hold the card near you smartphone/iPhone. And wait about ~ 20 sec to read its public key. \n Be sure the card is near your phone until you will see the key!")
        await new Promise(r => setTimeout(r, 20000));

        var securityCardPk = await NativeModules.NfcCardModule.getPublicKeyForDefaultPath();

        console.log("Public key from card = " + securityCardPk)
        alert("Public key from card = " + securityCardPk + ". Please remove security card for now.")
        await new Promise(r => setTimeout(r, 5000))


        TONClient.setLibrary(TONClientClass.clientPlatform);

        const ton = new TONClient();

        ton.config.setData({
            servers: [
                "eri01.net.everos.dev",
                "rbx01.net.everos.dev",
                "gra01.net.everos.dev",
            ],
        });

        ton.setup();

        const signingBox = new NfcCardSigningBox(ton)

        // Перед началом теста запросим адрес юзер-трекинга, мультисига, и их ключи
        await new Promise(r => setTimeout(r, 5000))
        alert("Requesting data about uTracking, multisig and recovery data for recording into card...")
        await new Promise(r => setTimeout(r, 5000))
        const testData = await requestRecoveryData()
        var recoveryDataJson = JSON.stringify( {
            surfPublicKey:  testData.multisig.keyPair.public,
            multisigAddress:  testData.multisig.address,
            p1: testData.cards[0].P1,
            cs: testData.cards[0].CS
        })

        console.log(recoveryDataJson)

        // Заберем из полученных данных ключи и адреса
        Object.assign(uTracking, R.pick(['keyPair', 'address', 'encryptionPublicKey'], testData.uTracking))
        Object.assign(multisig, R.pick(['keyPair', 'address'], testData.multisig))

        // Для теста добавим в мультисиг второго кастодиана - публичный ключ юзер-трекинга

        const ownersPKs = [multisig.keyPair.public]

        console.log("ownersPKs with one Custodian (Surf) = " + ownersPKs)
        alert("Multisig addr = " + testData.multisig.address + ", Surf public key = " + multisig.keyPair.public)
        await new Promise(r => setTimeout(r, 5000))
        alert("Password = " + testData.cards[0].P1 + ", common secret = " + testData.cards[0].CS)

        const reqConfirms = 2
        const { imageBase64 } = multisig.package
        const { codeBase64 } = await ton.contracts.getCodeFromImage({ imageBase64 })
        const { hash } = await ton.contracts.getBocHash({ bocBase64: codeBase64 })

        const custodianSurf = {
            keyPair: {
                public: multisig.keyPair.public,
                secret: multisig.keyPair.secret,
            }
        }

        //   Добавляет второго кастодиана карту
        {
            await new Promise(r => setTimeout(r, 5000))
            alert("Start adding 2nd Custodian security card into multisig")
            console.log("Start adding 2nd Custodian security card into multisig")

            ownersPKs.push(securityCardPk)
            console.log("ownersPKs with two Custodians (Surf, security card) = " + ownersPKs)
            Toast.show("ownersPKs with two Custodians (Surf, security card) = " + ownersPKs)
        
            await new Promise(r => setTimeout(r, 5000))
            alert("Start submitUpdate request by Serf pk to multisig. Please wait.")
            const { output } = await run(ton)({ ...multisig, ...custodianSurf }, 'submitUpdate', {
                codeHash: `0x${hash}`,
                owners: ownersPKs.map((k) => `0x${k}`),
                reqConfirms,
            })
            const { updateId } = output
            alert("submitUpdate is done")

            await new Promise(r => setTimeout(r, 5000))
            alert("Start executeUpdate request to multisig. Please wait.")
            await run(ton)({ ...multisig, ...custodianSurf }, 'executeUpdate', { updateId, code: codeBase64 })
            alert("executeUpdate is done")

            await new Promise(r => setTimeout(r, 5000))
            alert( 'OK, now custodians are Surf and security card:' + ownersPKs )
            console.log('OK, now custodians are Surf and security card:', ownersPKs)
        }

        await new Promise(r => setTimeout(r, 5000))
        console.log('Start registration in recovery service')
        alert('Start registration in recovery service')

        const recoveryServicePK = utils.strip0x(
            await utils
                .runLocalWithPredicateAndRetries(ton)(R.path(['output', 'key']))(integrationConfig, 'getKey', {
                    id: 10,
                })
                .then(R.path(['output', 'key'])),
        )

        // Helper. Возвращает публичный ключ шифрования SCSC контракта
        const getSCSCEncPK = (serviceId) =>
            utils
                .runLocalWithPredicateAndRetries(ton)(R.path(['output', 'key']))(integrationConfig, 'getKey', {
                    id: serviceId,
                })
            .then(R.path(['output', 'key']))

        // Helper. Шифрует данные naclBox
        // Returns hex string
        const encrypt = async (json) =>
            utils
                .naclBoxContainer(ton)(
                    uTracking.keyPair.secret,
                    uTracking.encryptionPublicKey,
                    utils.strip0x(await getSCSCEncPK(8)), // SCSC service has id == 8
                    json,
                )
            .catch(exit)

        const fname = `${uTracking.encryptionPublicKey}.2fa.html`

        console.log("URL = " + url2FA + fname)

        await new Promise(r => setTimeout(r, 5000));
        console.log("Start 2FA code verification")
        alert("Start 2FA code verifiation")

        // Запросим 2FA код. Это гарантированно старый код, еще с прошлого запуска. он нам не подойдет
        // Кроме того его может вообще не быть
        await new Promise(r => setTimeout(r, 5000))
        alert("Request oldCode2FA code")
        const oldCode2FA = await request2FA(fname)
        console.log("oldCode2FA = " + { oldCode2FA })

        await new Promise(r => setTimeout(r, 5000))
        alert("oldCode2FA = " + { oldCode2FA })

        // Шифрует email пользователя открытым ключом SC-сервиса, подписывает полученное сообщение закрытым ключом пользователя Surf
        await new Promise(r => setTimeout(r, 5000))
        alert('Reset registration process')
        console.log('Reset registration process')
        await utils.run(ton)(uTracking, 'stopRecovery', {})

        await new Promise(r => setTimeout(r, 5000))
        alert('Send requestRecoveryRegistration for userTracking address ' + uTracking.address)
        console.log('Send requestRecoveryRegistration for userTracking address %s', uTracking.address)
        const request = await encrypt({ email, action })
        await utils.run(ton)(uTracking, 'requestRecoveryRegistration', { request })
    
        await new Promise(r => setTimeout(r, 5000))
        alert('requestRecoveryRegistration request is done')

        // Читаем в цикле файл `fname`, пока в нем не появится 2FA код
        await new Promise(r => setTimeout(r, 5000))
        alert('Requesting correct 2FA code...')
        console.log('Requesting correct 2FA code...')
  
        let code2FA
        while (true) {
            console.log("request2FA.... ")
            Toast.show("request2FA.... ")
            code2FA = await request2FA(fname)
            console.log("New code2FA = " + { code2FA })
            if (code2FA && (oldCode2FA ? code2FA !== oldCode2FA : true)) {
                await new Promise(r => setTimeout(r, 5000))
                console.log('Got correct 2FA code %s', code2FA)
                alert('Got correct 2FA code ' + code2FA)
                break
            }
            await new Promise(r => setTimeout(r, 5000))
        }

        await new Promise(r => setTimeout(r, 5000))
        console.log('Sending WRONG old 2FA code')
        alert('Sending WRONG old 2FA code for test')
        const encOldCode2FA = await encrypt({ code2FA: oldCode2FA })
        await utils.run(ton)(uTracking, 'send2FA', { code2FA: encOldCode2FA  })

        await new Promise(r => setTimeout(r, 5000))
        alert('Sending WRONG 2FA code for test is done')

        await new Promise(r => setTimeout(r, 5000))
        alert('Wait for recovery status')
        let recoveryStatus
        while (!recoveryStatus) {
            recoveryStatus = await utils
                .runLocalWithPredicateAndRetries(ton)(R.T)(uTracking, 'getRecoveryStatus', {})
            .then(R.path(['output', 'recoveryStatus']))
            console.log("recoveryStatus " + recoveryStatus)
            await new Promise(r => setTimeout(r, 5000))
            console.log('waiting....')
        }
        await new Promise(r => setTimeout(r, 5000))
        alert('Recovery status = ' + recoveryStatus)
        if (recoveryStatus === '0x7' || recoveryStatus === '0x4') {
            exit(`Something went wrong. We sent incorrect 2FA code, but got recoveryStatus (success: 0x07  OR 0x04 )`, 0)
        }

        // Subscribe on messages from userTracking contract
        await new Promise(r => setTimeout(r, 5000))
        console.log('Waiting for the 2FA check answer')
        alert('Waiting for the 2FA check answer')

        await new Promise(r => setTimeout(r, 5000))
        console.log('2FA check failed, now sending right 2FA code')
        alert('2FA check failed, now sending right 2FA code')
        const encCode2FA = await encrypt({ code2FA })
        await utils.run(ton)(uTracking, 'send2FA', { code2FA: encCode2FA })
        await new Promise(r => setTimeout(r, 5000))
        alert('Sending correct 2FA code is done')
        console.log('Sending correct 2FA code is done')

        let recoveryStatusForCorrectCase = '0x2';
        while (recoveryStatusForCorrectCase !== '0x4') {
            recoveryStatusForCorrectCase = await utils
                .runLocalWithPredicateAndRetries(ton)(R.T)(uTracking, 'getRecoveryStatus', {})
                .then(R.path(['output', 'recoveryStatus']))
            console.log("recoveryStatus " + recoveryStatusForCorrectCase)
            await new Promise(r => setTimeout(r, 5000))
            console.log('waiting....')
        }
        await new Promise(r => setTimeout(r, 5000))
        alert('Recovery status = ' + recoveryStatusForCorrectCase)
        if (recoveryStatusForCorrectCase !== '0x4') {
            exit(`Something went wrong. We sent correct 2FA code, but got recoveryStatus not equal to 0x04 (fail)`, 0)
        }

        await new Promise(r => setTimeout(r, 5000))
        alert('Correct 2FA code verification is done.')
        console.log('Correct 2FA code verification is done.')

        await new Promise(r => setTimeout(r, 5000))
        alert('Requesting recovery data.')
        console.log('Requesting recovery data.')
        let encryptedDataFromRecoveryService
        while (!encryptedDataFromRecoveryService) {
            encryptedDataFromRecoveryService = await utils
                .runLocalWithPredicateAndRetries(ton)(R.T)(uTracking, 'getRecoveryData', {})
            .then(R.path(['output', 'recoveryData']))
            console.log(encryptedDataFromRecoveryService)
            await new Promise(r => setTimeout(r, 5000))
            console.log('waiting....')
        }
        await new Promise(r => setTimeout(r, 5000))
        alert('Encrypted Recovery data = ' + encryptedDataFromRecoveryService)


        const [part1, part2] = JSON.parse(
            Buffer.from(encryptedDataFromRecoveryService, 'hex').toString('utf-8'),
        )

        const json1 = await utils.openNaclBoxContainer(
            ton,
            uTracking.keyPair.secret,
            recoveryServicePK,
            Buffer.from(JSON.stringify(part1), 'utf-8').toString('hex'),
        )

        const json2 = part2
            ? await utils.openNaclBoxContainer(
                  ton,
                  uTracking.keyPair.secret,
                  recoveryServicePK,
                  Buffer.from(JSON.stringify(part2), 'utf-8').toString('hex'),
              )
            : null

        console.log(JSON.stringify(json1))
        console.log(JSON.stringify(json2))


        if (json1.pub_key && json2.aes_key) {
            await new Promise(r => setTimeout(r, 5000));
            alert("Start adding 3d Custodian HSM into multisig")
            console.log("Start adding 3d Custodian HSM into multisig")
                    

            // Добавляем 3го кастодиан в мультисиг
            {
                ownersPKs.push(json1.pub_key)
                await new Promise(r => setTimeout(r, 5000))
                alert('Public key from recovery service = ' + json1.pub_key)
                console.log('Public key from recovery service = ' + json1.pub_key)
    
                //  Эту транзу засабмитил custodianB
                await new Promise(r => setTimeout(r, 5000))
                alert("Start submitUpdate request to multisig by security card. Please wait.")
                const { output } = await runWithSigningBox(ton)(signingBox, { ...multisig }, 'submitUpdate', {
                    codeHash: `0x${hash}`,
                    owners: ownersPKs.map((k) => `0x${k}`),
                    reqConfirms,
                })
                const { updateId } = output
                                
                await new Promise(r => setTimeout(r, 5000))
                alert("Done submitUpdate by security card")
            
    
                // Подтвердил и выполнил custodianA
                await new Promise(r => setTimeout(r, 5000))
                alert("Start confirmUpdate by Serf pk. Please wait.")
                await run(ton)({ ...multisig, ...custodianSurf}, 'confirmUpdate', { updateId })
                await new Promise(r => setTimeout(r, 5000))
                alert("Done confirmUpdate by Serf")
    
                await new Promise(r => setTimeout(r, 5000))
                alert("Start executeUpdate by security card. Please wait.")
    
                await runWithSigningBox(ton)(signingBox, { ...multisig }, 'executeUpdate', { updateId, code: codeBase64 })
    
                await new Promise(r => setTimeout(r, 5000))
                alert("Done executeUpdate by security card")
    
                await new Promise(r => setTimeout(r, 5000))
    
                console.log('OK, now custodians are: Surf, security card, HSM', ownersPKs)
                alert('OK, now custodians are: Surf, security card, HSM', ownersPKs)
            }
    
            var aesKeyBytes = aesjs.utils.hex.toBytes(json2.aes_key);
            console.log("aesKeyBytes.length : " + aesKeyBytes.length);
    
            await new Promise(r => setTimeout(r, 5000))
            alert("aesKeyBytes.length : " + aesKeyBytes.length)
    
            await new Promise(r => setTimeout(r, 5000))
            alert("aesKey from recovery service: " + json2.aes_key)
    
            console.log("Recovery data to record into card : " + recoveryDataJson);
            var recoveryDataBytes = aesjs.utils.utf8.toBytes(recoveryDataJson);
    
            await new Promise(r => setTimeout(r, 5000))
            alert("Recovery data to record into card : " + recoveryDataJson)
    
            // The counter is optional, and if omitted will begin at 1
            var aesCtr = new aesjs.ModeOfOperation.ctr(aesKeyBytes, new aesjs.Counter(5));
            var encryptedBytes = aesCtr.encrypt(recoveryDataBytes);
    
            // To print or store the binary data, you may convert it to hex
            var encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);
            console.log("Encrypted recovery data : " + encryptedHex);
            console.log("Encrypted recovery data length : " + encryptedHex.length);
    
            await new Promise(r => setTimeout(r, 5000))
            alert("Encrypted recovery data : " + encryptedHex)
    
            await new Promise(r => setTimeout(r, 5000))
            alert("Hold the card near you smartphone/iPhone. And wait about ~ 20 sec to read its public key. \n Be sure the card is near your phone until you will see the key!")
            
            await new Promise(r => setTimeout(r, 20000));
            var addRes = await NativeModules.NfcCardModule.addRecoveryData(encryptedHex)
            console.log("add Recovery data into card result  = " + addRes)
            await new Promise(r => setTimeout(r, 5000))
            alert("add Recovery data into card result  = " + addRes)
    
            await new Promise(r => setTimeout(r, 5000))
            console.log('Done!')
            alert('Done!')
            exit(`Test passed!`, 0)
        }
    
        console.log("finish")

   } catch (e) {
    exit(e.message)
   }
}
Example #28
Source File: baseX.js    From RRWallet with MIT License 4 votes vote down vote up
module.exports = function base(ALPHABET) {
  if (ALPHABET.length >= 255) throw new TypeError("Alphabet too long");

  const BASE_MAP = new Uint8Array(256);
  BASE_MAP.fill(255);

  for (let i = 0; i < ALPHABET.length; i++) {
    const x = ALPHABET.charAt(i);
    const xc = x.charCodeAt(0);

    if (BASE_MAP[xc] !== 255) throw new TypeError(x + " is ambiguous");
    BASE_MAP[xc] = i;
  }

  const BASE = ALPHABET.length;
  const LEADER = ALPHABET.charAt(0);
  const FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
  const iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up

  function encode(source) {
    if (!Buffer.isBuffer(source)) throw new TypeError("Expected Buffer");
    if (source.length === 0) return "";

    // Skip & count leading zeroes.
    let zeroes = 0;
    let length = 0;
    let pbegin = 0;
    const pend = source.length;

    while (pbegin !== pend && source[pbegin] === 0) {
      pbegin++;
      zeroes++;
    }

    // Allocate enough space in big-endian base58 representation.
    const size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
    const b58 = new Uint8Array(size);

    // Process the bytes.
    while (pbegin !== pend) {
      let carry = source[pbegin];

      // Apply "b58 = b58 * 256 + ch".
      let i = 0;
      for (let it = size - 1; (carry !== 0 || i < length) && it !== -1; it--, i++) {
        carry += (256 * b58[it]) >>> 0;
        b58[it] = carry % BASE >>> 0;
        carry = (carry / BASE) >>> 0;
      }

      if (carry !== 0) throw new Error("Non-zero carry");
      length = i;
      pbegin++;
    }

    // Skip leading zeroes in base58 result.
    let it = size - length;
    while (it !== size && b58[it] === 0) {
      it++;
    }

    // Translate the result into a string.
    let str = LEADER.repeat(zeroes);
    for (; it < size; ++it) str += ALPHABET.charAt(b58[it]);

    return str;
  }

  function decodeUnsafe(source) {
    if (typeof source !== "string") throw new TypeError("Expected String");
    if (source.length === 0) return Buffer.alloc(0);

    let psz = 0;

    // Skip leading spaces.
    if (source[psz] === " ") return;

    // Skip and count leading '1's.
    let zeroes = 0;
    let length = 0;
    while (source[psz] === LEADER) {
      zeroes++;
      psz++;
    }

    // Allocate enough space in big-endian base256 representation.
    const size = ((source.length - psz) * FACTOR + 1) >>> 0; // log(58) / log(256), rounded up.
    const b256 = new Uint8Array(size);

    // Process the characters.
    while (source[psz]) {
      // Decode character
      let carry = BASE_MAP[source.charCodeAt(psz)];

      // Invalid character
      if (carry === 255) return;

      let i = 0;
      for (let it = size - 1; (carry !== 0 || i < length) && it !== -1; it--, i++) {
        carry += (BASE * b256[it]) >>> 0;
        b256[it] = carry % 256 >>> 0;
        carry = (carry / 256) >>> 0;
      }

      if (carry !== 0) throw new Error("Non-zero carry");
      length = i;
      psz++;
    }

    // Skip trailing spaces.
    if (source[psz] === " ") return;

    // Skip leading zeroes in b256.
    let it = size - length;
    while (it !== size && b256[it] === 0) {
      it++;
    }

    const vch = Buffer.allocUnsafe(zeroes + (size - it));
    vch.fill(0x00, 0, zeroes);

    let j = zeroes;
    while (it !== size) {
      vch[j++] = b256[it++];
    }

    return vch;
  }

  function decode(string) {
    const buffer = decodeUnsafe(string);
    if (buffer) return buffer;

    throw new Error("Non-base" + BASE + " character");
  }

  return {
    encode: encode,
    decodeUnsafe: decodeUnsafe,
    decode: decode,
  };
};