Skip to content

Commit

Permalink
Merge pull request #139 from nautls/remove-own-serializer
Browse files Browse the repository at this point in the history
Replace own serializer with Fleet's
  • Loading branch information
arobsn authored Jun 2, 2024
2 parents b3863aa + 8d49559 commit 7f86ce9
Show file tree
Hide file tree
Showing 16 changed files with 119 additions and 202 deletions.
1 change: 0 additions & 1 deletion src/@types/tiny-secp256k1.d.ts

This file was deleted.

4 changes: 2 additions & 2 deletions src/api/ergo/addresses.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { P2PK_TREE_PREFIX, NETWORK } from "@/constants/ergo";
import { NETWORK, P2PK_TREE_PREFIX } from "@/constants/ergo";
import { ErgoBoxCandidate } from "@/types/connector";
import { last } from "@fleet-sdk/common";
import { ErgoAddress } from "@fleet-sdk/core";
import { last } from "lodash-es";

export function getChangeAddress(
outputs: ErgoBoxCandidate[],
Expand Down
8 changes: 4 additions & 4 deletions src/api/ergo/eip28.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { hex, randomBytes } from "@fleet-sdk/crypto";

/**
* Creates a EIP-28 signing message
* @param message
* @param origin
* @returns the signing message formatted as "signingMessage;origin;timestamp;randomBytes"
*/
export function buildEip28ResponseMessage(message: string, origin: string): string {
const buffer = Buffer.from(new Uint8Array(32));
crypto.getRandomValues(buffer);

return `${message};${origin};${Math.floor(Date.now() / 1000)};${buffer.toString("hex")}`;
const rand = hex.encode(randomBytes(32));
return `${message};${origin};${Math.floor(Date.now() / 1000)};${rand}`;
}
65 changes: 65 additions & 0 deletions src/api/ergo/extraction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { P2PK_TREE_PREFIX, PK_HEX_LENGTH, SIGMA_CONSTANT_PK_MATCHER } from "@/constants/ergo";
import { Registers } from "@/types/connector";
import { ErgoTree } from "ergo-lib-wasm-browser";
import { Box, isEmpty, uniq } from "@fleet-sdk/common";
import { addressFromErgoTree, addressFromPk } from "./addresses";

export function extractPksFromRegisters(registers: Registers): string[] {
const pks: string[] = [];
for (const register of Object.values(registers)) {
const pk = extractPkFromSigmaConstant(register);
if (pk) pks.push(pk);
}

return pks;
}

export function extractPksFromP2SErgoTree(ergoTree: string): string[] {
const pks: string[] = [];
const tree = ErgoTree.from_base16_bytes(ergoTree);
const len = tree.constants_len();
for (let i = 0; i < len; i++) {
const constant = tree.get_constant(i)?.encode_to_base16();
const pk = extractPkFromSigmaConstant(constant);
if (pk) pks.push(pk);
}

return pks;
}

export function extractPkFromSigmaConstant(constant?: string): string | undefined {
if (!constant) return;

const result = SIGMA_CONSTANT_PK_MATCHER.exec(constant);
if (!result) return;

for (let i = 0; i < result.length; i++) {
if (result[i] && result[i].length === PK_HEX_LENGTH) {
return result[i];
}
}
}

function extractAddressesFromInput(input: Box): string[] {
if (input.ergoTree.startsWith(P2PK_TREE_PREFIX)) {
return [addressFromErgoTree(input.ergoTree)];
}

let pks = extractPksFromP2SErgoTree(input.ergoTree);
if (input.additionalRegisters) {
pks = pks.concat(extractPksFromRegisters(input.additionalRegisters));
}

if (isEmpty(pks)) return [];

const addresses: string[] = [];
for (const pk of uniq(pks)) {
addresses.push(addressFromPk(pk));
}

return addresses;
}

export function extractAddressesFromInputs(inputs: Box[]) {
return inputs.map((input) => extractAddressesFromInput(input)).flat();
}
2 changes: 1 addition & 1 deletion src/api/ergo/hdKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export default class HdKey {
}

public get extendedPublicKey(): Uint8Array {
if (this.#xpk) {
if (!this.#xpk) {
const decoded = base58check.decode(this.#change.extendedPublicKey);
this.#xpk = this.normalizeExtendedKey(decoded);
}
Expand Down
10 changes: 10 additions & 0 deletions src/api/ergo/serialization.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { isUndefined } from "@fleet-sdk/common";
import { Coder } from "@fleet-sdk/crypto";
import { parse } from "@fleet-sdk/serializer";

export function sigmaDecode<T>(value: string, coder?: Coder<unknown, T>) {
const v = parse<T>(value, "safe");
if (isUndefined(v)) return;

return coder ? coder.encode(v) : v;
}
124 changes: 0 additions & 124 deletions src/api/ergo/sigmaSerializer.ts

This file was deleted.

10 changes: 6 additions & 4 deletions src/api/ergo/transaction/interpreter/outputInterpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ import { ErgoBoxCandidate } from "@/types/connector";
import { decimalize, toBigNumber } from "@/utils/bigNumbers";
import BigNumber from "bignumber.js";
import { find, findIndex, first, isEmpty } from "lodash-es";
import { decodeColl } from "@/api/ergo/sigmaSerializer";
import { sigmaDecode } from "@/api/ergo/serialization";
import { StateAssetInfo } from "@/types/internal";
import { isBabelContract } from "../../babelFees";
import { AddressType, ErgoAddress, Network } from "@fleet-sdk/core";
import { EIP12UnsignedInput } from "@fleet-sdk/common";
import { utf8 } from "@fleet-sdk/crypto";

export type OutputAsset = {
tokenId: string;
Expand Down Expand Up @@ -155,15 +156,16 @@ export class OutputInterpreter {
};
}

const decimals = parseInt(decodeColl(this._box.additionalRegisters["R6"]) ?? "");
const decodedDecimals = sigmaDecode(this._box.additionalRegisters["R6"], utf8);
const decimals = decodedDecimals ? parseInt(decodedDecimals) : undefined;
return {
tokenId: token.tokenId,
name: decodeColl(this._box.additionalRegisters["R4"]) ?? "",
name: sigmaDecode(this._box.additionalRegisters["R4"], utf8) ?? "",
decimals,
amount: decimals
? decimalize(toBigNumber(token.amount), decimals)
: toBigNumber(token.amount),
description: decodeColl(this._box.additionalRegisters["R5"]) ?? "",
description: sigmaDecode(this._box.additionalRegisters["R5"], utf8) ?? "",
minting: true
};
}
Expand Down
6 changes: 3 additions & 3 deletions src/api/ergo/transaction/interpreter/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Amount, TokenAmount } from "@fleet-sdk/common";
import { Amount, Box, TokenAmount } from "@fleet-sdk/common";
import { OutputAsset } from "@/api/ergo/transaction/interpreter/outputInterpreter";
import { ErgoBoxCandidate, Token, UnsignedInput } from "@/types/connector";
import { ErgoBoxCandidate, Token } from "@/types/connector";
import { StateAssetInfo } from "@/types/internal";
import { decimalize, toBigNumber } from "@/utils/bigNumbers";

Expand All @@ -16,7 +16,7 @@ export const tokensToOutputAssets = (tokens: Token[], assetInfo: StateAssetInfo)
});
};

export const boxCandidateToBoxAmounts = (b: ErgoBoxCandidate | UnsignedInput) => {
export const boxCandidateToBoxAmounts = (b: ErgoBoxCandidate | Box) => {
return {
value: b.value.toString(),
assets: b.assets
Expand Down
38 changes: 6 additions & 32 deletions src/api/ergo/transaction/prover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@ import WebUSBTransport from "@ledgerhq/hw-transport-webusb";
import {
Address,
BlockHeaders,
ErgoBoxCandidate,
ErgoBoxes,
ErgoStateContext,
NonMandatoryRegisterId,
PreHeader,
SecretKey,
SecretKeys,
Expand Down Expand Up @@ -184,7 +182,7 @@ export class Prover {
ergoTree: Buffer.from(wasmOutput.ergo_tree().sigma_serialize_bytes()),
creationHeight: wasmOutput.creation_height(),
tokens: mapTokens(wasmOutput.tokens()),
registers: this.serializeRegisters(wasmOutput)
registers: Buffer.from(wasmOutput.serialized_additional_registers())
});
}

Expand Down Expand Up @@ -268,9 +266,9 @@ export class Prover {
}

private _signInputs(
unsigned: UnsignedTransaction,
unspentBoxes: ErgoBoxes,
dataInputBoxes: ErgoBoxes,
tx: UnsignedTransaction,
inputs: ErgoBoxes,
dataInputs: ErgoBoxes,
headers: Header[],
inputsToSign: number[]
) {
Expand All @@ -288,17 +286,11 @@ export class Prover {
);

const preHeader = PreHeader.from_block_header(blockHeaders.get(0));
const signContext = new ErgoStateContext(preHeader, blockHeaders);
const context = new ErgoStateContext(preHeader, blockHeaders);
const signed: SignedInput[] = [];

for (const index of inputsToSign) {
const result = wallet.sign_tx_input(
index,
signContext,
unsigned,
unspentBoxes,
dataInputBoxes
);
const result = wallet.sign_tx_input(index, context, tx, inputs, dataInputs);

signed.push({
boxId: result.box_id().to_str(),
Expand All @@ -309,24 +301,6 @@ export class Prover {
return signed;
}

private serializeRegisters(box: ErgoBoxCandidate): Buffer {
const registerEnum = NonMandatoryRegisterId;
if (!box.register_value(registerEnum.R4)) {
return Buffer.from([]);
}

const registers = [
Buffer.from(box.register_value(registerEnum.R4)?.sigma_serialize_bytes() ?? []),
Buffer.from(box.register_value(registerEnum.R5)?.sigma_serialize_bytes() ?? []),
Buffer.from(box.register_value(registerEnum.R6)?.sigma_serialize_bytes() ?? []),
Buffer.from(box.register_value(registerEnum.R7)?.sigma_serialize_bytes() ?? []),
Buffer.from(box.register_value(registerEnum.R8)?.sigma_serialize_bytes() ?? []),
Buffer.from(box.register_value(registerEnum.R9)?.sigma_serialize_bytes() ?? [])
].filter((b) => b.length > 0);

return Buffer.concat([...[Buffer.from([registers.length])], ...registers]);
}

private reportState(state: PartialSignState) {
if (!this._callbackFn) {
return;
Expand Down
Loading

0 comments on commit 7f86ce9

Please sign in to comment.