All files validate.ts

11.17% Statements 21/188
4.02% Branches 9/224
17.24% Functions 5/29
11.17% Lines 21/188

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 5661x 1x 1x 1x 1x   1x 1x 1x     1x 1x 1x     1x 1x 1x 1x     1x 1x 1x 1x                                                                                                                                                 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
import { InfuraProvider } from '@ethersproject/providers';
import MerkleTools from '@settlemint/merkle-tools';
import Axios from 'axios';
import { sha3_512 } from 'js-sha3';
import { Readable } from 'stream';
 
export enum Protocol {
  BITCOIN = 'bitcoin',
  ETHEREUM = 'ethereum',
}
 
export enum NetworkName {
  MAINNET = 'mainnet',
  TESTNET = 'testnet',
}
 
export enum DataType {
  STRING = 'STRING',
  FILE = 'FILE',
  HASH = 'HASH',
}
 
export enum SealStatus {
  CONFIRMED = 'confirmed',
  FAILED = 'failed',
  PENDING = 'pending',
}
 
export interface ISeal {
  id: string;
  dataHash: string;
  anchors: IAnchors<IAnchor>;
  signatures?: ISignatures;
  signinvites?: ISignInvites;
  sealed: string;
}
 
export interface IAnchor {
  transactionId: string;
  nodeUrl: string;
  explorer: string;
  merkleRoot: string;
  proof: IProof[];
  exists?: boolean;
}
 
export interface IInviteAnchor extends IAnchor {
  invites?: { [inviteId: string]: ISignInvite };
  transactionStatus: SealStatus;
}
 
export interface ISignInvite {
  proof: IProof[];
  hash: string;
}
 
export interface IAnchors<Type> {
  ethereum?: {
    [networkId: string]: Type;
  };
  bitcoin?: {
    mainnet?: Type;
    testnet?: Type;
  };
}
 
export interface IProof {
  right?: string;
  left?: string;
}
 
export interface ISignatures {
  ethereum?: {
    [signerAddress: string]: {
      transactionId: string;
      nodeUrl: string;
      explorer: string;
      signature: string;
      signed: string;
      transactionStatus: SealStatus;
    };
  };
}
 
export interface IConfig {
  bitcoin?: {
    url?: string;
    apiKey?: string;
  };
 
  ethereum?: {
    apiKey?: string;
  };
}
 
export interface ISignInvites {
  anchors: IAnchors<IInviteAnchor>;
}
export class CertiMintValidation {
  public constructor(protected config: IConfig = {}) {}
 
  public async updateSeal(seal: ISeal): Promise<ISeal> {
    seal.signatures = await this.resolveSignatures(seal.signatures);
    if (seal.signinvites) {
      seal.signinvites = await this.resolveSignInvites(seal.signinvites);
    }
 
    return seal;
  }
 
  public async validateSealAndData(
    seal: ISeal,
    data: string,
    dataType: DataType
  ): Promise<SealStatus> {
    const hash = await this.hashForData(data, dataType);
 
    const validationStatus = await this.validateSeal(seal);
 
    return hash.toLowerCase() === seal.dataHash.toLowerCase() ? validationStatus : SealStatus.FAILED;
  }
 
  public async validateSeal(seal: ISeal): Promise<SealStatus> {
    const validAnchors = await this.validateAnchors(
      seal.anchors,
      seal.dataHash
    );
 
    const validSignatures = seal.signatures
      ? await this.validateSignatures(seal.signatures)
      : SealStatus.CONFIRMED;
    const validSignInvites = seal.signinvites
      ? await this.validateSignInvites(seal.signinvites)
      : SealStatus.CONFIRMED;
 
    if (
      validSignatures === SealStatus.FAILED ||
      validSignInvites === SealStatus.FAILED ||
      !validAnchors
    ) {
      return SealStatus.FAILED;
    }
 
    if (
      validSignatures === SealStatus.PENDING ||
      validSignInvites === SealStatus.PENDING
    ) {
      return SealStatus.PENDING;
    }
 
    return SealStatus.CONFIRMED;
  }
 
  private async hashForData(
    data: string | Readable | Blob,
    dataType: DataType
  ) {
    let hex: string;
    switch (dataType) {
      case DataType.FILE:
        if (data instanceof Readable) {
          hex = await this.streamToHashForNode(data);
        } else if (data instanceof Blob) {
          hex = await this.streamToHashForBrowser(data);
        } else {
          throw new Error(
            `ERROR: File is not Readable or Blob for ${dataType}`
          );
        }
        break;
      case DataType.STRING:
        if (data instanceof Readable || data instanceof Blob) {
          throw new Error(
            `ERROR: Data cannot be Readable or Blob for ${dataType}`
          );
        }
        hex = sha3_512(data);
        break;
      case DataType.HASH:
        if (data instanceof Readable || data instanceof Blob) {
          throw new Error(
            `ERROR: Data cannot be Readable or Blob for ${dataType}`
          );
        }
        hex = data;
        break;
      default:
        throw new Error(`ERROR: unknown type ${dataType}`);
    }
 
    return hex;
  }
 
  private async validateAnchors(
    anchors: IAnchors<IAnchor>,
    dataHash: string
  ): Promise<boolean> {
    let isValid = true;
    for (const protocol of Object.keys(anchors)) {
      switch (protocol) {
        case Protocol.ETHEREUM:
          isValid =
            isValid && (await this.validateEthereumAnchor(anchors, dataHash));
          break;
        case Protocol.BITCOIN:
          isValid =
            isValid && (await this.validateBitcoinAnchor(anchors, dataHash));
          break;
 
        default:
          throw new Error(`Unsupported protocol ${protocol}`);
      }
    }
 
    return isValid;
  }
 
  private async validateEthereumAnchor(
    anchors: IAnchors<IAnchor>,
    dataHash: string
  ) {
    let isValid = true;
 
    for (const chainId of Object.keys(anchors[Protocol.ETHEREUM] || [])) {
      const anchor = anchors[Protocol.ETHEREUM]?.[chainId];
      if (anchor) {
 
        if(anchor.nodeUrl.match(/mintnet/)){
          // the mintnet network is discontinued.
          // since all anchors are also on the mainnet and bitcoin, no security is lost.
          return true;
        }
 
        const provider = InfuraProvider.getWebSocketProvider('homestead', this.config.ethereum.apiKey);
 
        console.log(`Trying to validate ${this.addHexPrefix(anchor.transactionId)} on Infura`);
        const tx = await provider.getTransaction(
          this.addHexPrefix(anchor.transactionId)
        );
 
        if(!tx){
          console.log(`Not found:`, anchor)
 
          return false;
        }
 
        anchor.exists = tx.data === this.addHexPrefix(anchor.merkleRoot);
 
        const merkleTools = new MerkleTools({
          hashType: 'SHA3-512',
        });
 
        const validProof = merkleTools.validateProof(
          anchor.proof,
          dataHash,
          anchor.merkleRoot
        );
 
        isValid = isValid && anchor.exists && validProof;
      }
    }
 
    return isValid;
  }
 
  private async validateBitcoinAnchor(
    anchors: IAnchors<IAnchor>,
    dataHash: string
  ) {
    let isValid = true;
    for (const networkName of Object.keys(anchors[Protocol.BITCOIN] || [])) {
      const anchor = anchors[Protocol.BITCOIN]?.[networkName];
      if (anchor) {
        try {
          const txId = anchor.transactionId;
          const tx = await Axios.get(
            this.buildTxUrl(
              this.config?.bitcoin?.url ||
                'https://api.blockcypher.com/v1/btc/main',
              txId
            )
          );
 
          const txOutputs = tx.data.outputs;
          let merkleRoot: string | null = null;
          for (const output of txOutputs) {
            if (output.data_hex !== undefined && output.data_hex !== null) {
              merkleRoot = output.data_hex;
            }
          }
 
          if (!merkleRoot) {
            throw new Error('Merkle root is undefined');
          }
 
          anchor.exists = merkleRoot === anchor.merkleRoot;
 
          const merkleTools = new MerkleTools({
            hashType: 'SHA3-512',
          });
 
          const validProof = merkleTools.validateProof(
            anchor.proof,
            dataHash,
            anchor.merkleRoot
          );
 
          isValid = isValid && anchor.exists && validProof;
        } catch (error) {
          if (error.response !== undefined && error.response.status === 429) {
            throw new Error(
              'Too many request to the blockcypher api, please add an apikey or upgrade your blockcypher plan'
            );
            // tslint:disable-next-line: unnecessary-else
          } else {
            throw error;
          }
        }
      }
    }
 
    return isValid;
  }
 
  private async validateSignatures(
    signatures: ISignatures
  ): Promise<SealStatus> {
    let isValid = SealStatus.CONFIRMED;
    for (const protocol of Object.keys(signatures)) {
      for (const address of Object.keys(signatures[protocol])) {
        // This should technically not be neccessary since we only anchor signatures on Ethereum
        if (protocol === Protocol.ETHEREUM) {
          const signature = signatures[protocol]?.[address];
          if (signature) {
            const signatureProvider = InfuraProvider.getWebSocketProvider('homestead', this.config.ethereum.apiKey);
 
            const tx = await signatureProvider.getTransaction(
              this.addHexPrefix(signature.transactionId)
            );
            if (tx) {
              if (tx.data === this.addHexPrefix(signature.signature)) {
                isValid =
                  isValid === SealStatus.CONFIRMED
                    ? SealStatus.CONFIRMED
                    : isValid;
              } else {
                return SealStatus.FAILED;
              }
            }
            if (
              !tx &&
              signature.transactionStatus &&
              signature.transactionStatus === SealStatus.PENDING
            ) {
              isValid = SealStatus.PENDING;
            }
 
            if (
              !tx &&
              (!signature.transactionStatus ||
                signature.transactionStatus !== SealStatus.PENDING)
            ) {
              return SealStatus.FAILED;
            }
          }
        }
      }
    }
 
    return isValid;
  }
 
  private async validateSignInvites(
    signInvites: ISignInvites
  ): Promise<SealStatus> {
    let isValid = SealStatus.CONFIRMED;
 
    if (signInvites && signInvites.anchors) {
      const signInviteAnchors = signInvites.anchors;
      for (const protocol of Object.keys(signInviteAnchors)) {
        for (const chainId of Object.keys(signInviteAnchors[protocol])) {
          // This should technically not be neccessary since we only anchor signinvites on Ethereum
          if (protocol === Protocol.ETHEREUM) {
            const signInvite = signInviteAnchors[protocol]?.[chainId];
            if (signInvite) {
              const signInviteProvider = InfuraProvider.getWebSocketProvider('homestead', this.config.ethereum.apiKey);
 
              const tx = await signInviteProvider.getTransaction(
                this.addHexPrefix(signInvite.transactionId)
              );
 
              if (tx) {
                signInvite.exists =
                  tx.data === this.addHexPrefix(signInvite.merkleRoot);
                isValid =
                  isValid === SealStatus.CONFIRMED
                    ? SealStatus.CONFIRMED
                    : isValid;
 
                const merkleTools = new MerkleTools({
                  hashType: 'SHA3-512',
                });
                let validProof = true;
 
                for (const inviteId of Object.keys(signInvite.invites || {})) {
                  const inviteAnchor = signInvite.invites?.[inviteId];
 
                  if (inviteAnchor) {
                    validProof = merkleTools.validateProof(
                      inviteAnchor.proof,
                      inviteAnchor.hash,
                      signInvite.merkleRoot
                    );
                  }
                }
 
                if (!validProof || !signInvite.exists) {
                  return SealStatus.FAILED;
                }
              }
              if (
                !tx &&
                signInvite.transactionStatus &&
                signInvite.transactionStatus === SealStatus.PENDING
              ) {
                isValid = SealStatus.PENDING;
              }
 
              if (
                !tx &&
                (!signInvite.transactionStatus ||
                  signInvite.transactionStatus !== SealStatus.PENDING)
              ) {
                return SealStatus.FAILED;
              }
            }
          }
        }
      }
    }
 
    return isValid;
  }
 
  private async resolveSignatures(
    signatures?: ISignatures
  ): Promise<ISignatures | undefined> {
    if (signatures) {
      for (const protocol of Object.keys(signatures || [])) {
        for (const address of Object.keys(signatures?.[protocol] || [])) {
          // This should technically not be neccessary since we only anchor signatures on Ethereum
          if (protocol === Protocol.ETHEREUM) {
            const signature = signatures?.[protocol]?.[address];
            if (signature) {
              const signatureProvider = InfuraProvider.getWebSocketProvider('homestead', this.config.ethereum.apiKey);
 
              const tx = await signatureProvider.getTransaction(
                this.addHexPrefix(signature.transactionId)
              );
              if (tx) {
                if (tx.data === this.addHexPrefix(signature.signature)) {
                  // tslint:disable-next-line: ban-ts-ignore
                  // @ts-ignore
                  signatures[protocol][address].transactionStatus =
                    SealStatus.CONFIRMED;
                }
              }
            }
          }
        }
      }
    }
 
    return signatures;
  }
 
  private async resolveSignInvites(
    signInvites: ISignInvites
  ): Promise<ISignInvites> {
    if (signInvites && signInvites.anchors) {
      const signInviteAnchors = signInvites.anchors;
      for (const protocol of Object.keys(signInviteAnchors)) {
        for (const chainId of Object.keys(signInviteAnchors[protocol])) {
          // This should technically not be neccessary since we only anchor signinvites on Ethereum
          if (protocol === Protocol.ETHEREUM) {
            const signInvite = signInviteAnchors[protocol]?.[chainId];
            if (signInvite) {
              const signInviteProvider = InfuraProvider.getWebSocketProvider('homestead', this.config.ethereum.apiKey);
 
              const tx = await signInviteProvider.getTransaction(
                this.addHexPrefix(signInvite.transactionId)
              );
 
              if (
                tx &&
                tx.data === this.addHexPrefix(signInvite.merkleRoot) &&
                signInviteAnchors[protocol]
              ) {
                // tslint:disable-next-line: ban-ts-ignore
                // @ts-ignore
                signInviteAnchors[protocol][chainId].transactionStatus =
                  SealStatus.CONFIRMED;
              }
            }
          }
        }
      }
    }
 
    return signInvites;
  }
 
  private addHexPrefix(fromValue: string) {
    return this.isHexPrefixed(fromValue) ? fromValue : '0x' + fromValue;
  }
 
  private isHexPrefixed(valueToCheck: string) {
    return valueToCheck.substring(0, 2) === '0x';
  }
 
  private async streamToHashForNode(stream: Readable): Promise<string> {
    return new Promise((resolve, reject) => {
      const allData: Buffer[] = [];
      stream.on('data', (chunk) => {
        allData.push(chunk);
      });
      stream.on('end', () => {
        resolve(sha3_512(Buffer.concat(allData)));
      });
      stream.on('error', (error) => {
        reject(error);
      });
    });
  }
 
  private async streamToHashForBrowser(file: Blob): Promise<string> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onloadend = () => {
        resolve(sha3_512(reader.result as ArrayBuffer));
      };
      reader.onerror = () => {
        reject('Could not read file');
      };
      reader.readAsArrayBuffer(file);
    });
  }
 
  private buildTxUrl(baseUrl: string, txId: string) {
    const apiKeyParam = this.config?.bitcoin?.apiKey
      ? `?token=${this.config.bitcoin.apiKey}`
      : '';
 
    return `${baseUrl}/txs/${txId}${apiKeyParam}`;
  }
 
  private addInfuraApiKey(baseUrl: string) {
    return baseUrl.match(/infura.io/) && this.config?.ethereum?.apiKey
      ? baseUrl.replace(
          /infura.io/,
          `infura.io/v3/${this.config.ethereum.apiKey}`
        )
      : baseUrl;
  }
}