# xdvplatform-wallet

> A wallet for documents and tokens

Latest version **4.0.4** (published 2021-01-24) · MIT license · 0 weekly downloads

## Install

```sh
npm install xdvplatform-wallet
pnpm add xdvplatform-wallet
yarn add xdvplatform-wallet
bun add xdvplatform-wallet
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 4.0.4 |
| Published | 2021-01-24 |
| First published | 2020-06-15 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 37 |
| Unpacked size | 303.4 KB |
| Known vulnerabilities | 0 (+46 in 7 direct dependencies) |
| Install scripts | no |
| Author | @molekilla |
| Maintainers | molekilla |

## Links

- npm: https://www.npmjs.com/package/xdvplatform-wallet
- Repository: https://github.com/molekilla/xdv-fe-builder
- Homepage: https://github.com/molekilla/xdv-fe-builder#readme
- Issues: https://github.com/molekilla/xdv-fe-builder/issues
- npm.io page: https://npm.io/package/xdvplatform-wallet

## Dependencies (37)

- [bs58](https://npm.io/package/bs58.md) ^4.0.1
- [cids](https://npm.io/package/cids.md) ^0.8.1
- [rxjs](https://npm.io/package/rxjs.md) ^6.5.5
- [delay](https://npm.io/package/delay.md) ^4.3.0
- [rasha](https://npm.io/package/rasha.md) ^1.2.5
- [ec-key](https://npm.io/package/ec-key.md) 0.0.4
- [ethers](https://npm.io/package/ethers.md) ^5.0.24
- [moment](https://npm.io/package/moment.md) ^2.26.0
- [slip39](https://npm.io/package/slip39.md) ^0.1.7
- [hash.js](https://npm.io/package/hash.js.md) ^1.1.7
- [p12-pem](https://npm.io/package/p12-pem.md) ^1.0.4
- [pouchdb](https://npm.io/package/pouchdb.md) ^7.2.1
- [elliptic](https://npm.io/package/elliptic.md) ^6.5.2
- [node-jose](https://npm.io/package/node-jose.md) ^1.1.4
- [webcrypto](https://npm.io/package/webcrypto.md) ^0.1.1
- [jwk-to-pem](https://npm.io/package/jwk-to-pem.md) ^2.0.3
- [node-forge](https://npm.io/package/node-forge.md) ^0.9.1
- [xml-crypto](https://npm.io/package/xml-crypto.md) ^1.5.3
- [xmlbuilder2](https://npm.io/package/xmlbuilder2.md) ^2.1.2
- [crypto-pouch](https://npm.io/package/crypto-pouch.md) ^3.1.3
- [did-resolver](https://npm.io/package/did-resolver.md) ^1.1.0
- [jsonwebtoken](https://npm.io/package/jsonwebtoken.md) ^8.5.1
- [ed25519-hd-key](https://npm.io/package/ed25519-hd-key.md) ^1.1.2
- [jwt-ed25519-tn](https://npm.io/package/jwt-ed25519-tn.md) 0.0.3
- [class-validator](https://npm.io/package/class-validator.md) ^0.12.2
- [hdkey-secp256r1](https://npm.io/package/hdkey-secp256r1.md) ^1.1.0
- [noble-bls12-381](https://npm.io/package/noble-bls12-381.md) ^0.2.3
- [ethr-did-resolver](https://npm.io/package/ethr-did-resolver.md) ^2.2.0
- [@decent-bet/solido](https://npm.io/package/@decent-bet/solido.md) ^1.1.6
- [arraybuffer-concat](https://npm.io/package/arraybuffer-concat.md) 0.0.1
- [multihashing-async](https://npm.io/package/multihashing-async.md) ^0.8.1
- [crypto-key-composer](https://npm.io/package/crypto-key-composer.md) ^0.1.3
- [@chainsafe/bls-hd-key](https://npm.io/package/@chainsafe/bls-hd-key.md) 0.0.1
- [arraybuffer-to-string](https://npm.io/package/arraybuffer-to-string.md) ^1.0.2
- [solido-provider-ethers](https://npm.io/package/solido-provider-ethers.md) ^2.0.1
- [text-encoding-polyfill](https://npm.io/package/text-encoding-polyfill.md) ^0.6.7
- [@zondax/filecoin-signing-tools](https://npm.io/package/@zondax/filecoin-signing-tools.md) ^0.11.0

## Recent versions

- 4.0.4 (latest) — 2021-01-24
- 4.0.3 — 2021-01-24
- 4.0.2 — 2021-01-24
- 4.0.1 — 2021-01-23
- 3.1.3 — 2020-12-15
- 3.1.2 — 2020-12-15
- 3.1.1 — 2020-12-15
- 3.1.0 — 2020-12-15
- 3.0.8 — 2020-12-02
- 3.0.7 — 2020-12-01
- 3.0.6 — 2020-12-01
- 3.0.5 — 2020-12-01
- 3.0.4 — 2020-10-21
- 3.0.3 — 2020-10-20
- 3.0.2 — 2020-10-20
- … 16 more at https://npm.io/package/xdvplatform-wallet/versions

## README

# XDV Platform Wallet


`npm i xdvplatform-wallet`

### Features

### crypto

- Supports for JWT, DID, JWE, XmlDsig, CMS (X509)
- Algorithms included: `secp256k1`, `secp256r1`, `ed25519`, `rsa` and upcoming `bls`
- `Keystore`, `HD Key`, `DER`, `JWK` and `PEM` support out of the box
- Support for output to `LD Crypto Suite` key pairs for `ecdsa` and `ed25519`
- More features planned like `bls` and `schnorr` for multi sig scenarios

#### API

####  Wallet

A wallet instance is always required to start working with Wallet API. You configure RxJS subjects to handle password management between UI subscriber and Wallet API.

`Creating a wallet with createWallet`


```typescript
    const wallet = new Wallet();
    this.wallet.onRequestPassphraseSubscriber.subscribe(async (i) => {
      this.canUnlock = true;
      this.loading = true;
      if (i.type === 'wallet') {
        this.passphraseSubject.subscribe((passphrase) =>
          this.wallet.onRequestPassphraseWallet.next({ type: 'ui', passphrase })
        );
      } else {
        this.canUnlock = false;
        this.loading = false;
      }
    });

    let { id } = await wallet.createWallet(this.password, null, mnemonic);
```

`Unlocking using open`

Now with that id, be sure to save it somewhere, you always query the Wallet API DB to open the wallet. It will ask you for your password if you configure the RxJS Subscribers as defined in the previous step.

```typescript
 await this.wallet.open(id);
```


`Wallet.generateMnemonic`

Creates a new mnemonic

```typescript
     const mnemonic = Wallet.generateMnemonic();
     const selectedWallet = await Wallet.createHDWallet({ mnemonic, password: '123password' });
```


`deriveChild`

Creates a new child HD Wallet

```typescript
      const child1 = wallet.deriveChild(1, `m/44'/60'/0'/0`);
      const child2 = wallet.deriveChild(2, `m/44'/60'/0'/0`);
      const child3 = wallet.deriveChild(3, `m/44'/60'/0'/0`);
```

`deriveFromPath`

Creates a new child HD Wallet

```typescript
      const child1 = wallet.deriveFromPath(`m/44'/60'/0'/0/1`);
      const child2 = wallet.deriveFromPath(`m/44'/60'/0'/0/2`);
      const child3 = wallet.deriveFromPath(`m/44'/60'/0'/0/3`);
```


`getEd25519`

Creates a new Ed25519 curve 

```typescript
    const kp = await wallet.getEd25519();
```


`getP256`

Creates a new P256/secp256r1 curve 

```typescript
    const kp = await wallet.getP256();
```


`getES256k`

Creates a new secp256k1 curve 

```typescript
    const kp = await wallet.getES256k();
```


`getRSA256Standalone`

Creates a new RSA key pair. This key pair is not generated from HD Wallet seed. 

```typescript
    const kp = await wallet.getRSA256Standalone();
```

`getBlsMasterKey`

Creates a new BLS key pair. Returns an object. 

```typescript
    const kp = wallet.getBlsMasterKey();
    const deriveValidatorKey1 = await kp.deriveValidatorKeys(1);
```
####  KeyConvert

Handles key pair convertion from / to `PEM`, `DER` or `JWK`. Some algorithm also returns `JSON-LD` compatible exports.

`KeyConvert.getX509RSA`

Converts a RSA key pair. Available exports: JWK, PEM and LD.


```typescript
  const key = await Wallet.getRSA256Standalone();
        const issuer: X509Info = {
          stateOrProvinceName: 'PA',
          organizationName: 'RM',
          organizationalUnitName: 'Engineering',
          commonName: 'Rogelio Morrell',
          countryName: 'Panama',
          localityName: 'Panama'
        };
        const { jwk, pem } = await KeyConvert.getX509RSA(key);
        const jwt = await JWTService.sign(pem, {
          testing: 'testing'
        }, {
          iat: (new Date(2020, 10, 10)).getTime(),
          iss: '0x4198258023eD0D6fae5DBCF3Af2aeDaaA363571F',
          sub: 'document',
          aud: 'receptor',
          nbf: (new Date(2020, 10, 10)).getTime(),
        });

```

`KeyConvert.getP256`

Converts a P256 key pair. Available exports: JWK, DER, PEM and LD.


```typescript

    const mnemonic = Wallet.generateMnemonic();
    const opts = { mnemonic, password: '123password' };
    const keystore = await Wallet.createHDWallet(opts);
    expect(JSON.parse(keystore).version).equal(3);

    const wallet = await Wallet.unlock(keystore, opts.password);
    const key = wallet.getP256();

    const pem = (await KeyConvert.getP256(key)).pem;
    const jwt = await JWTService.sign(pem, {
        testing: 'testing'
    }, {
        iat: (new Date(2020, 10, 10)).getTime(),
        iss: '0x4198258023eD0D6fae5DBCF3Af2aeDaaA363571F',
        sub: 'document',
        aud: 'receptor',
        nbf: (new Date(2020, 10, 10)).getTime(),
    });


```

`KeyConvert.getES256K`

Converts a ES256K key pair. Available exports: JWK, DER, PEM and LD.


```typescript
    const wallet = await Wallet.unlock(keystore, opts.password);
    const pem = (await KeyConvert.getES256K(wallet.getES256K())).pem;
```


`KeyConvert.getRSA`

Converts a RSA key pair. Available exports: JWK and PEM as pemAsPrivate and pemAsPublic.


```typescript
   const key = await Wallet.getRSA256Standalone();
    const pem = (await KeyConvert.getRSA(key)).pemAsPrivate;
```

`KeyConvert.getEd25519`

Converts a Ed25519 key pair. Available exports: DER and PEM.


```typescript
    const mnemonic = Wallet.generateMnemonic();
    const opts = { mnemonic, password: '123password' };
    const keystore = await Wallet.createHDWallet(opts);

    const wallet = await Wallet.unlock(keystore, opts.password);
    const key = wallet.getEd25519();

    const pem = (await KeyConvert.getEd25519(key)).pem;
    const jwt = await JWTService.sign(pem, {
        testing: 'testing'
    }, {
        iat: (new Date(2020, 10, 10)).getTime(),
        iss: '0x4198258023eD0D6fae5DBCF3Af2aeDaaA363571F',
        sub: 'document',
        aud: 'receptor',
        nbf: (new Date(2020, 10, 10)).getTime(),
    });

```

`KeyConvert.createLinkedDataJsonFormat`

Creates a Linked Data suite json format from a LD Suite export.

```typescript
    const mnemonic = Wallet.generateMnemonic();
    const opts = { mnemonic, password: '123password' };
    const keystore = await Wallet.createHDWallet(opts);

    const wallet = await Wallet.unlock(keystore, opts.password);

    const kp = wallet.getP256();
    const kpJwk = await KeyConvert.getP256(kp);

    // Create LD Crypto Suite - p256 / Sepc256r1
    const ldCrypto = await KeyConvert
        .createLinkedDataJsonFormat(LDCryptoTypes.Sepc256r1, kpJwk.ldSuite);

    // Create IPFS key storage lock
    const session = await xdvMethod.createIpldSession(kpJwk.pem);

    // Create DID document with an did-ipid based issuer
    const did = await DIDDocumentBuilder
        .createDID({
        issuer: session.key,
        verificationKeys: [ldCrypto.toPublicKey()],
        authenticationKeys: [ldCrypto.toAuthorizationKey()]
        });

    // Signing
    const signed = await  JWTService.sign(kpJwk.pem, {
        ...did,
        testing: 'testing'
    }, {
        iat: (new Date(2020, 10, 10)).getTime(),
        iss: '0x4198258023eD0D6fae5DBCF3Af2aeDaaA363571F',
        sub: 'document',
        aud: 'receptor',
        nbf: (new Date(2020, 10, 10)).getTime(),
    });
    
```

####  JWTService

Signs and verifies JWT.

`JWTService.decodeWithSignature`

Decodes a JWT


```typescript
    // Sign as JWT
    let signed = await JWTService.sign(kpJwk.pem, {
        ...did,
        testing: 'testing'
    }, {
        iat: (new Date(2020, 10, 10)).getTime(),
        iss: '0x4198258023eD0D6fae5DBCF3Af2aeDaaA363571F',
        sub: 'document',
        aud: 'receptor',
        nbf: (new Date(2020, 10, 10)).getTime(),
    });

    // Decoded
    const decoded = await JWTService.decodeWithSignature(signed);
    expect(!!decoded.signature).equal(true)
    expect(!!decoded.data).equal(true)
    expect(!!decoded.header).equal(true)
    expect(!!decoded.payload).equal(true)
```

`JWTService.sign`

Signs a JWT


```typescript
    // Unlock wallet
    const wallet = await Wallet.unlock(keystore, opts.password);

    // Create key
    const kp = wallet.getP256();
    const kpJwk = await KeyConvert.getP256(kp);

    // Create LD Crypto Suite - p256 / Sepc256r1
    const ldCrypto = await KeyConvert
        .createLinkedDataJsonFormat(LDCryptoTypes.Sepc256r1, kpJwk.ldSuite);

    // Create DID id from PEM keypair and store it variable  
    const session = await xdvMethod.createIpldSession(kpJwk.pem);

    // Set DID
    localStorage['recentlyStoreDID'] = session.key;

    // Create DID document with an did-ipid based issuer
    let did = await DIDDocumentBuilder
        .createDID({
        issuer: session.key,
        verificationKeys: [ldCrypto.toPublicKey()],
        authenticationKeys: [ldCrypto.toAuthorizationKey()]
        });

    // Sign as JWT
    let signed = await JWTService.sign(kpJwk.pem, {
        ...did,
        testing: 'testing'
    }, {
        iat: (new Date(2020, 10, 10)).getTime(),
        iss: '0x4198258023eD0D6fae5DBCF3Af2aeDaaA363571F',
        sub: 'document',
        aud: 'receptor',
        nbf: (new Date(2020, 10, 10)).getTime(),
    });
```

`JWTService.verify`

Verifies a JWT


```typescript
    // get document with a CID and DID
    const resolver = await xdvMethod.getResolver(localStorage['recentlyStoreCID']);
    const doc = await resolver.xdv(localStorage['recentlyStoreDID']);

    // unlock wallet
    let wallet = await Wallet.unlock(localStorage['ks'], localStorage['ps']);

    // create new key pairs
    const kp = wallet.getP256();
    const kpJwk = await KeyConvert.getP256(kp);


    // decrypt
    const obj = await JOSEService.decrypt(kpJwk.jwk, doc.encrypted);
    const verified = await JWTService.verify(kpJwk.pem,(<Buffer> obj.plaintext).toString('utf8'), 'receptor');
```


####  JOSEService

Encrypts and decrypts JWT.

`JOSEService.encrypt`

Encrypts a string or buffer payload


```typescript
    // Unlock wallet
    const wallet = await Wallet.unlock(keystore, opts.password);

    // Create key
    const kp = wallet.getP256();
    const kpJwk = await KeyConvert.getP256(kp);

    // Create LD Crypto Suite - p256 / Sepc256r1
    const ldCrypto = await KeyConvert
        .createLinkedDataJsonFormat(LDCryptoTypes.Sepc256r1, kpJwk.ldSuite);

    // Create DID id from PEM keypair and store it variable  
    const session = await xdvMethod.createIpldSession(kpJwk.pem);

    // Set DID
    localStorage['recentlyStoreDID'] = session.key;

    // Create DID document with an did-ipid based issuer
    let did = await DIDDocumentBuilder
        .createDID({
        issuer: session.key,
        verificationKeys: [ldCrypto.toPublicKey()],
        authenticationKeys: [ldCrypto.toAuthorizationKey()]
        });

    // Sign as JWT
    let signed = await JWTService.sign(kpJwk.pem, {
        ...did,
        testing: 'testing'
    }, {
        iat: (new Date(2020, 10, 10)).getTime(),
        iss: '0x4198258023eD0D6fae5DBCF3Af2aeDaaA363571F',
        sub: 'document',
        aud: 'receptor',
        nbf: (new Date(2020, 10, 10)).getTime(),
    });

    // Encrypt JWT
    const encrypted = await JOSEService.encrypt(kpJwk.jwk, signed);
```

`JOSEService.decrypt`

Decrypts a cipher


```typescript
    // get document with a CID and DID
    const resolver = await xdvMethod.getResolver(localStorage['recentlyStoreCID']);
    const doc = await resolver.xdv(localStorage['recentlyStoreDID']);

    // unlock wallet
    let wallet = await Wallet.unlock(localStorage['ks'], localStorage['ps']);

    // create new key pairs
    const kp = wallet.getP256();
    const kpJwk = await KeyConvert.getP256(kp);


    // decrypt
    const obj = await JOSEService.decrypt(kpJwk.jwk, doc.encrypted);
    const verified = await JWTService.verify(kpJwk.pem,(<Buffer> obj.plaintext).toString('utf8'), 'receptor');


```


####  X509

`X509.createSelfSignedCertificateFromRSA`


Creates a self sign certificate from a RSA key pair

```typescript
    const issuer: X509Info = {
        stateOrProvinceName: 'PA',
        organizationName: 'RM',
        organizationalUnitName: 'Engineering',
        commonName: 'Rogelio Morrell',
        countryName: 'Panama',
        localityName: 'Panama'
    };
    const rsaKey = await Wallet.getRSA256Standalone();

    const rsaKeyExports = await KeyConvert.getX509RSA(rsaKey);
    const selfSignedCert = X509.createSelfSignedCertificateFromRSA(
      rsaKeyExports.pemAsPrivate, rsaKeyExports.pemAsPublic, issuer);
    const signedDocuments = await XmlDsig.signFEDocument(rsaKeyExports.pem, selfSignedCert, latestFEDocument);
```


####  XmlDsig (FE specific)

Signs FE XML Documents

`XmlDsig.signFEDocument`

Signs a Factura Electronica de Panama document

```typescript
    const issuer: X509Info = {
        stateOrProvinceName: 'PA',
        organizationName: 'RM',
        organizationalUnitName: 'Engineering',
        commonName: 'Rogelio Morrell',
        countryName: 'Panama',
        localityName: 'Panama'
    };
    const rsaKey = await Wallet.getRSA256Standalone();

    const rsaKeyExports = await KeyConvert.getX509RSA(rsaKey);
    const selfSignedCert = X509.createSelfSignedCertificateFromRSA(
      rsaKeyExports.pemAsPrivate, rsaKeyExports.pemAsPublic, issuer);
    const signedDocuments = await XmlDsig.signFEDocument(rsaKeyExports.pemAsPrivate, selfSignedCert, latestFEDocument);
```

####  CMSSigner

Signs CMS Documents

`CMSSigner.sign`

Signs a CMS document

```typescript
    const issuer: X509Info = {
        stateOrProvinceName: 'PA',
        organizationName: 'RM',
        organizationalUnitName: 'Engineering',
        commonName: 'Rogelio Morrell',
        countryName: 'Panama',
        localityName: 'Panama'
    };
    const rsaKey = await Wallet.getRSA256Standalone();

    const rsaKeyExports = await KeyConvert.getX509RSA(rsaKey);
    const selfSignedCert = X509.createSelfSignedCertificateFromRSA(
      rsaKeyExports.pemAsPrivate, rsaKeyExports.pemAsPublic, issuer);
    const res = CMSSigner.sign(selfSignedCert,
        rsaKeyExports.pemAsPrivate,
        fs.readFileSync(__dirname + '/fixtures/cms.pdf'));
```

#### `did`

- Supports for basic DID JSON schemas
- `DID JWT` signing and validation using `xdvplatform-tools/crypto` API
- Includes `did-method-xdv` with resolver

#### API

 

`Wallet.createHDWallet`

Creates a new random HD Wallet

```typescript
  const keystore = await Wallet.createHDWallet({ password: 'password123' });
```



#### `fe`

- Includes most of the API specifications for `Factura Electronica DGI Panama` up to September 2018 specification
- Planned features: `CUFE` generation and `QR` generation



#### `dv`

- Digito Verificador for RUC Natural Person based on algorithm from Registro Publico de Panama. 
- Client that calls a read only function in a Solidity smart contract

##### Usage

```typescript
        const nodeUrl = '...node url';
        const isMainnet = true;
        const account = '...your ethereum accpunt';

        const dv = new DV(account, nodeUrl, isMainnet);
        
        // initialize contracts
        await dv.initialize();
        
        // call calculate
        // input is 
        // { type, segments 1 to  4}
        // For more information, visit https://dv.auth2factor.com
        const resp = await dv.calculate(CedulaInputTypes.N,
            [0, 8],
            [0, 0],
            [7, 1, 3],
            [2, 2, 3]);

        expect(resp).equals('11');
```

@molekilla, Rogelio Morrell C. 
Copyright 2020-2021

##### MIT License

---
_Source: https://npm.io/package/xdvplatform-wallet · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
