/* Copyright 2018 - 2022 The Alephium Authors This file is part of the alephium project. The library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the library. If not, see . */ import { Buffer } from 'buffer/' import * as cryptojs from 'crypto-js' import * as crypto from 'crypto' import fs from 'fs' import { promises as fsPromises } from 'fs' import { NodeProvider } from '../api' import { node } from '../api' import { SignDeployContractTxParams, SignExecuteScriptTxParams, SignerWithNodeProvider } from '../signer' import * as ralph from './ralph' import { bs58, binToHex, contractIdFromAddress, assertType, Eq } from '../utils' export abstract class Common { readonly sourceCodeSha256: string readonly functions: node.FunctionSig[] static readonly importRegex = new RegExp('^import "[a-z][a-z_0-9]*.ral"', 'mg') static readonly contractRegex = new RegExp('^TxContract [A-Z][a-zA-Z0-9]*', 'mg') static readonly interfaceRegex = new RegExp('^Interface [A-Z][a-zA-Z0-9]* \\{', 'mg') static readonly scriptRegex = new RegExp('^TxScript [A-Z][a-zA-Z0-9]*', 'mg') private static _artifactCache: Map = new Map() static artifactCacheCapacity = 20 protected static _getArtifactFromCache(codeHash: string): Contract | Script | undefined { return this._artifactCache.get(codeHash) } protected static _putArtifactToCache(contract: Contract): void { if (!this._artifactCache.has(contract.codeHash)) { if (this._artifactCache.size >= this.artifactCacheCapacity) { const keyToDelete = this._artifactCache.keys().next().value this._artifactCache.delete(keyToDelete) } this._artifactCache.set(contract.codeHash, contract) } } constructor(sourceCodeSha256: string, functions: node.FunctionSig[]) { this.sourceCodeSha256 = sourceCodeSha256 this.functions = functions } protected static _contractPath(fileName: string): string { if (fileName.endsWith('.json')) { return `./contracts/${fileName.slice(0, -5)}` } else { return `./contracts/${fileName}` } } protected static _artifactPath(fileName: string): string { if (fileName.endsWith('.json')) { return `./artifacts/${fileName}` } else { return `./artifacts/${fileName}.json` } } protected static _artifactsFolder(): string { return './artifacts/' } protected static async _handleImports(contractStr: string, importsCache: string[]): Promise { const localImportsCache: string[] = [] let result = contractStr.replace(Common.importRegex, (match) => { localImportsCache.push(match) return '' }) for (const myImport of localImportsCache) { const fileName = myImport.slice(8, -1) if (!importsCache.includes(fileName)) { importsCache.push(fileName) const importContractStr = await Common._loadContractStr(fileName, importsCache, (code) => Contract.checkCodeType(fileName, code) ) result = result.concat('\n', importContractStr) } } return result } protected static async _loadContractStr( fileName: string, importsCache: string[], validate: (fileName: string) => void ): Promise { const contractPath = this._contractPath(fileName) const contractBuffer = await fsPromises.readFile(contractPath) const contractStr = contractBuffer.toString() validate(contractStr) return Common._handleImports(contractStr, importsCache) } static checkFileNameExtension(fileName: string): void { if (!fileName.endsWith('.ral')) { throw new Error('Smart contract file name should end with ".ral"') } } protected static async _from( provider: NodeProvider, fileName: string, loadContractStr: (fileName: string, importsCache: string[]) => Promise, compile: (provider: NodeProvider, fileName: string, contractStr: string, contractHash: string) => Promise ): Promise { Common.checkFileNameExtension(fileName) const contractStr = await loadContractStr(fileName, []) const contractHash = cryptojs.SHA256(contractStr).toString() const existingContract = this._getArtifactFromCache(contractHash) if (typeof existingContract !== 'undefined') { return existingContract as unknown as T } else { return compile(provider, fileName, contractStr, contractHash) } } protected _saveToFile(fileName: string): Promise { const artifactPath = Common._artifactPath(fileName) return fsPromises.writeFile(artifactPath, this.toString()) } abstract buildByteCodeToDeploy(initialFields?: Fields): string } export class Contract extends Common { readonly bytecode: string readonly codeHash: string readonly fieldsSig: node.FieldsSig readonly eventsSig: node.EventSig[] constructor( sourceCodeSha256: string, bytecode: string, codeHash: string, fieldsSig: node.FieldsSig, eventsSig: node.EventSig[], functions: node.FunctionSig[] ) { super(sourceCodeSha256, functions) this.bytecode = bytecode this.codeHash = codeHash this.fieldsSig = fieldsSig this.eventsSig = eventsSig } static checkCodeType(fileName: string, contractStr: string): void { const interfaceMatches = contractStr.match(Contract.interfaceRegex) if (interfaceMatches) { return } const contractMatches = contractStr.match(Contract.contractRegex) if (contractMatches === null) { throw new Error(`No contract found in: ${fileName}`) } else if (contractMatches.length > 1) { throw new Error(`Multiple contracts in: ${fileName}`) } else { return } } private static async loadContractStr(fileName: string, importsCache: string[]): Promise { return Common._loadContractStr(fileName, importsCache, (code) => Contract.checkCodeType(fileName, code)) } static async fromSource(provider: NodeProvider, fileName: string): Promise { if (!fs.existsSync(Common._artifactsFolder())) { fs.mkdirSync(Common._artifactsFolder(), { recursive: true }) } const contract = await Common._from( provider, fileName, (fileName, importCaches) => Contract.loadContractStr(fileName, importCaches), Contract.compile ) this._putArtifactToCache(contract) return contract } private static async compile( provider: NodeProvider, fileName: string, contractStr: string, contractHash: string ): Promise { const compiled = await provider.contracts.postContractsCompileContract({ code: contractStr }) const artifact = new Contract( contractHash, compiled.bytecode, compiled.codeHash, compiled.fields, compiled.events, compiled.functions ) await artifact._saveToFile(fileName) return artifact } // TODO: safely parse json static fromJson(artifact: any): Contract { if ( artifact.sourceCodeSha256 == null || artifact.bytecode == null || artifact.codeHash == null || artifact.fieldsSig == null || artifact.eventsSig == null || artifact.functions == null ) { throw Error('The artifact JSON for contract is incomplete') } const contract = new Contract( artifact.sourceCodeSha256, artifact.bytecode, artifact.codeHash, artifact.fieldsSig, artifact.eventsSig, artifact.functions ) this._putArtifactToCache(contract) return contract } // support both 'code.ral' and 'code.ral.json' static async fromArtifactFile(fileName: string): Promise { const artifactPath = Contract._artifactPath(fileName) const content = await fsPromises.readFile(artifactPath) const artifact = JSON.parse(content.toString()) return Contract.fromJson(artifact) } override toString(): string { return JSON.stringify( { sourceCodeSha256: this.sourceCodeSha256, bytecode: this.bytecode, codeHash: this.codeHash, fieldsSig: this.fieldsSig, eventsSig: this.eventsSig, functions: this.functions }, null, 2 ) } toState(fields: Fields, asset: Asset, address?: string): ContractState { const addressDef = typeof address !== 'undefined' ? address : Contract.randomAddress() return { address: addressDef, contractId: binToHex(contractIdFromAddress(addressDef)), bytecode: this.bytecode, codeHash: this.codeHash, fields: fields, fieldsSig: this.fieldsSig, asset: asset } } static randomAddress(): string { const bytes = crypto.randomBytes(33) bytes[0] = 3 return bs58.encode(bytes) } private async _test( provider: NodeProvider, funcName: string, params: TestContractParams, expectPublic: boolean, accessType: string ): Promise { const apiParams: node.TestContract = this.toTestContract(funcName, params) const apiResult = await provider.contracts.postContractsTestContract(apiParams) const methodIndex = typeof params.testMethodIndex !== 'undefined' ? params.testMethodIndex : this.getMethodIndex(funcName) const isPublic = this.functions[`${methodIndex}`].signature.indexOf('pub ') !== -1 if (isPublic === expectPublic) { const result = await this.fromTestContractResult(methodIndex, apiResult) return result } else { throw new Error(`The test method ${funcName} is not ${accessType}`) } } async testPublicMethod( provider: NodeProvider, funcName: string, params: TestContractParams ): Promise { return this._test(provider, funcName, params, true, 'public') } async testPrivateMethod( provider: NodeProvider, funcName: string, params: TestContractParams ): Promise { return this._test(provider, funcName, params, false, 'private') } toApiFields(fields?: Fields): node.Val[] { if (typeof fields === 'undefined') { return [] } else { return toApiFields(fields, this.fieldsSig) } } toApiArgs(funcName: string, args?: Arguments): node.Val[] { if (args) { const func = this.functions.find((func) => func.name == funcName) if (func == null) { throw new Error(`Invalid function name: ${funcName}`) } return toApiArgs(args, func) } else { return [] } } getMethodIndex(funcName: string): number { return this.functions.findIndex((func) => func.name === funcName) } toApiContractStates(states?: ContractState[]): node.ContractState[] | undefined { return typeof states != 'undefined' ? states.map((state) => toApiContractState(state)) : undefined } toTestContract(funcName: string, params: TestContractParams): node.TestContract { return { group: params.group, address: params.address, bytecode: this.bytecode, initialFields: this.toApiFields(params.initialFields), initialAsset: typeof params.initialAsset !== 'undefined' ? toApiAsset(params.initialAsset) : undefined, methodIndex: this.getMethodIndex(funcName), args: this.toApiArgs(funcName, params.testArgs), existingContracts: this.toApiContractStates(params.existingContracts), inputAssets: toApiInputAssets(params.inputAssets) } } static async fromCodeHash(codeHash: string): Promise { const cached = this._getArtifactFromCache(codeHash) if (typeof cached !== 'undefined') { return cached as Contract } const files = await fsPromises.readdir(Common._artifactsFolder()) for (const file of files) { if (file.endsWith('.ral.json')) { try { const contract = await Contract.fromArtifactFile(file) if (contract.codeHash === codeHash) { return contract as Contract } } catch (_) {} } } throw new Error(`Unknown code with code hash: ${codeHash}`) } static async getFieldsSig(state: node.ContractState): Promise { return Contract.fromCodeHash(state.codeHash).then((contract) => contract.fieldsSig) } async fromApiContractState(state: node.ContractState): Promise { const contract = await Contract.fromCodeHash(state.codeHash) return { address: state.address, contractId: binToHex(contractIdFromAddress(state.address)), bytecode: state.bytecode, initialStateHash: state.initialStateHash, codeHash: state.codeHash, fields: fromApiFields(state.fields, contract.fieldsSig), fieldsSig: await Contract.getFieldsSig(state), asset: fromApiAsset(state.asset) } } static ContractCreatedEvent: node.EventSig = { name: 'ContractCreated', signature: 'event ContractCreated(address:Address)', fieldNames: ['address'], fieldTypes: ['Address'] } static ContractDestroyedEvent: node.EventSig = { name: 'ContractDestroyed', signature: 'event ContractDestroyed(address:Address)', fieldNames: ['address'], fieldTypes: ['Address'] } static async fromApiEvent( event: node.ContractEventByTxId, codeHash: string | undefined ): Promise { let eventSig: node.EventSig if (event.eventIndex == -1) { eventSig = this.ContractCreatedEvent } else if (event.eventIndex == -2) { eventSig = this.ContractDestroyedEvent } else { const contract = await Contract.fromCodeHash(codeHash!) eventSig = contract.eventsSig[event.eventIndex] } return { blockHash: event.blockHash, contractAddress: event.contractAddress, name: eventSig.name, fields: fromApiEventFields(event.fields, eventSig) } } async fromTestContractResult(methodIndex: number, result: node.TestContractResult): Promise { const addressToCodeHash = new Map() addressToCodeHash.set(result.address, result.codeHash) result.contracts.forEach((contract) => addressToCodeHash.set(contract.address, contract.codeHash)) return { address: result.address, contractId: binToHex(contractIdFromAddress(result.address)), returns: fromApiArray(result.returns, this.functions[`${methodIndex}`].returnTypes), gasUsed: result.gasUsed, contracts: await Promise.all(result.contracts.map((contract) => this.fromApiContractState(contract))), txOutputs: result.txOutputs.map(fromApiOutput), events: await Promise.all( result.events.map((event) => { const contractAddress = event.contractAddress const codeHash = addressToCodeHash.get(contractAddress) if (typeof codeHash !== 'undefined' || event.eventIndex < 0) { return Contract.fromApiEvent(event, codeHash) } else { throw Error(`Cannot find codeHash for the contract address: ${contractAddress}`) } }) ) } } async paramsForDeployment(params: BuildDeployContractTx): Promise { const bytecode = this.buildByteCodeToDeploy(params.initialFields ? params.initialFields : {}) const signerParams: SignDeployContractTxParams = { signerAddress: params.signerAddress, bytecode: bytecode, initialAlphAmount: extractOptionalNumber256(params.initialAlphAmount), issueTokenAmount: extractOptionalNumber256(params.issueTokenAmount), initialTokenAmounts: params.initialTokenAmounts?.map(toApiToken), gasAmount: params.gasAmount, gasPrice: extractOptionalNumber256(params.gasPrice) } return signerParams } async transactionForDeployment( signer: SignerWithNodeProvider, params: Omit ): Promise { const signerParams = await this.paramsForDeployment({ ...params, signerAddress: (await signer.getAccounts())[0].address }) const response = await signer.buildContractCreationTx(signerParams) return fromApiDeployContractUnsignedTx(response) } buildByteCodeToDeploy(initialFields: Fields): string { return ralph.buildContractByteCode(this.bytecode, initialFields, this.fieldsSig) } } export class Script extends Common { readonly bytecodeTemplate: string readonly fieldsSig: node.FieldsSig constructor( sourceCodeSha256: string, bytecodeTemplate: string, fieldsSig: node.FieldsSig, functions: node.FunctionSig[] ) { super(sourceCodeSha256, functions) this.bytecodeTemplate = bytecodeTemplate this.fieldsSig = fieldsSig } static checkCodeType(fileName: string, contractStr: string): void { const scriptMatches = contractStr.match(this.scriptRegex) if (scriptMatches === null) { throw new Error(`No script found in: ${fileName}`) } else if (scriptMatches.length > 1) { throw new Error(`Multiple scripts in: ${fileName}`) } else { return } } private static async loadContractStr(fileName: string, importsCache: string[]): Promise { return Common._loadContractStr(fileName, importsCache, (code) => Script.checkCodeType(fileName, code)) } static async fromSource(provider: NodeProvider, fileName: string): Promise