Skip to content

Commit

Permalink
Data inputs [working] + P2S signing [wip]
Browse files Browse the repository at this point in the history
P2S outputs supported
P2S inputs do not seem to work - more testing is needed.
Yoroi signs them without returning any errors, but when submitted to the
network they are not accepted.
  • Loading branch information
rooooooooob committed May 4, 2021
1 parent 7f08891 commit 98aeeb0
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 16 deletions.
58 changes: 48 additions & 10 deletions packages/yoroi-ergo-connector/example/index.js
Expand Up @@ -56,7 +56,8 @@ function initDapp() {
button.textContent = "Send";
button.onclick = async function() {
status.innerText = "Creating transaction";
const donationAddr = "9fp6ERwLEF8u3Jvbii2msogFDUa9edxmvQKbwbwogXjLg7oXZSo";
const heightGT1337 = "5yE918nbfmCzFGNoh7wz"; // HEIGHT > 1337
const donationAddr = "9hD2Cw6yQL6zzrw3TFgKdwFkBdDdU3ro1xRFmjouDw4NYS2S5RD";
const creationHeight = 398959;
const amountToSend = parseInt(valueEntry.value, 10);
const amountToSendBoxValue = wasm.BoxValue.from_i64(wasm.I64.from_str(amountToSend.toString()));
Expand All @@ -70,7 +71,20 @@ function initDapp() {
asset.amount = parseInt(asset.amount);
}
return utxo;
})
});
// this is a box we created with that HEIGHT > 1337 as the ergo tree
utxos.unshift({
"additionalRegisters": {
},
"assets": [
],
"boxId": "0f0e4c71ccfbe7e749591ef2a906607b415deadee8c23a8d822517c4cd55374e",
"creationHeight": 398959,
"ergoTree": "100104f214d191a37300",
"index": 0,
"transactionId": "c93731f3a79a85f4c959785eb8d981ff0e03730c432dfb07da7049a9b0081027",
"value": 195800
});
console.log(`utxosValue: ${utxosValue}`);
console.log(`${utxosValue} - ${amountToSend} - ${wasm.TxBuilder.SUGGESTED_TX_FEE().as_i64().as_num()}`);
const changeValue = utxosValue - amountToSend - wasm.TxBuilder.SUGGESTED_TX_FEE().as_i64().as_num();
Expand All @@ -93,7 +107,12 @@ function initDapp() {
// changeValueBoxValue,
// wasm.Contract.pay_to_address(wasm.Address.from_base58(changeAddr)),
// creationHeight);
outputCandidates.add(donationBoxBuilder.build());
try {
outputCandidates.add(donationBoxBuilder.build());
} catch (e) {
console.log(`building error: ${e}`);
throw e;
}
//outputCandidates.add(changeBoxBuilder.build());
console.log(`utxosval: ${utxosValue}`);
const txBuilder = wasm.TxBuilder.new(
Expand All @@ -104,15 +123,34 @@ function initDapp() {
wasm.Address.from_base58(changeAddr),
wasm.BoxValue.SAFE_USER_MIN());
//changeValueBoxValue);

const dataInputs = new wasm.DataInputs();
// ranndom tx we sent via the connector before - not referenced in any smart contract right now
//dataInputs.add(new wasm.DataInput(wasm.BoxId.from_str("0f0e4c71ccfbe7e749591ef2a906607b415deadee8c23a8d822517c4cd55374e")));
txBuilder.set_data_inputs(dataInputs);
const tx = txBuilder.build().to_json();
console.log(`tx: ${tx}`);
console.log(`tx: ${JSON.stringify(tx)}`);
console.log(`original id: ${tx.id}`);
// sigma-rust doesn't support most compilation so manually insert it here
// this is HEIGHT > 1337 but in hex and without the checksum/etc for the address of the contract
//tx.outputs[0].ergoTree = "100104f214d191a37300";
// and we rebuild it using
const correctTx = wasm.UnsignedTransaction.from_json(JSON.stringify(tx)).to_json();
console.log(`new id: ${correctTx.id}`);
// we must use the exact order chosen as after 0.4.3 in sigma-rust
// this can change and might not use all the utxos as the coin selection
// might choose a more optimal amount
correctTx.inputs = correctTx.inputs.map(box => {
console.log(`box: ${JSON.stringify(box)}`);
const fullBoxInfo = utxos.find(utxo => utxo.boxId === box.boxId);
return {
...fullBoxInfo,
extension: {}
};
});
status.innerText = "Awaiting transaction signing";
console.log(`${JSON.stringify(correctTx)}`);
ergo
.sign_tx({
...tx,
inputs: utxos.map(utxo => ({ ...utxo, extension: {} })),
})
.sign_tx(correctTx)
.then(async signedTx => {
status.innerText = "Transaction signed - awaiting submission"
try {
Expand Down Expand Up @@ -153,4 +191,4 @@ if (typeof ergo_request_read_access === "undefined") {
div.appendChild(button);
});
initDapp();
}
}
2 changes: 1 addition & 1 deletion packages/yoroi-ergo-connector/example/package.json
Expand Up @@ -11,7 +11,7 @@
"start": "webpack-dev-server"
},
"devDependencies": {
"ergo-lib-wasm-browser": "0.4.3",
"ergo-lib-wasm-browser": "0.10.0",
"webpack": "^4.29.3",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5",
Expand Down
4 changes: 3 additions & 1 deletion packages/yoroi-extension/chrome/extension/background.js
Expand Up @@ -338,7 +338,9 @@ chrome.runtime.onMessage.addListener(async (
throw new Error('could not get all utxos');
}
const utxos = await canGetAllUtxos.getAllUtxos();
return await connectorSignTx(wallet, password, utxos, tx, indices);
const stateFetcher = await getStateFetcher(localStorageApi);
const bestBlock = await stateFetcher.getBestBlock({ network: wallet.getParent().getNetworkInfo() });
return await connectorSignTx(wallet, password, utxos, bestBlock, tx, indices);
},
db,
localStorageApi
Expand Down
31 changes: 29 additions & 2 deletions packages/yoroi-extension/chrome/extension/ergo-connector/api.js
Expand Up @@ -43,6 +43,8 @@ import { getReceiveAddress } from '../../../app/stores/stateless/addressStores';

import LocalStorageApi from '../../../app/api/localStorage/index';

import type { BestBlockResponse } from '../../../app/api/ergo/lib/state-fetch/types';

function paginateResults<T>(results: T[], paginate: ?Paginate): T[] {
if (paginate != null) {
const startIndex = paginate.page * paginate.limit;
Expand Down Expand Up @@ -217,9 +219,11 @@ export async function connectorSignTx(
publicDeriver: IPublicDeriver<ConceptualWallet>,
password: string,
utxos: any/* IGetAllUtxosResponse */,
bestBlock: BestBlockResponse,
tx: Tx,
indices: Array<number>
): Promise<ErgoTxJson> {
console.log('connectSignTx()');
const withLevels = asHasLevels(publicDeriver);
if (withLevels == null) {
throw new Error('wallet doesn\'t support levels');
Expand Down Expand Up @@ -262,13 +266,36 @@ export async function connectorSignTx(
const jsonBoxesToSign = utxosToSign.map(formatUtxoToBox);
processBoxesForSigmaRust(jsonBoxesToSign);
const txBoxesToSign = RustModule.SigmaRust.ErgoBoxes.from_boxes_json(jsonBoxesToSign);
console.log('data inputs');
const dataInputs = new RustModule.SigmaRust.DataInputs();
for (const dataInput of tx.dataInputs) {
const boxId = RustModule.SigmaRust.BoxId.from_str(dataInput.boxId);
dataInputs.add(new RustModule.SigmaRust.DataInput(boxId));
}
// We could modify the best block backend to return this information for the previous block
// but I'm guessing that votes of the previous block isn't useful for the current one
// and I'm also unsure if any of these 3 would impact signing or not.
// Maybe version would later be used in the ergoscript context?
const headerJson = JSON.stringify({
version: 2, // TODO: where to get version? (does this impact signing?)
parentId: bestBlock.hash,
timestamp: Date.now(),
nBits: 682315684511744, // TODO: where to get difficulty? (does this impact signing?)
height: bestBlock.height + 1,
votes: "040000", // TODO: where to get votes? (does this impact signing?)
});
console.log(`block header: ${headerJson}`);
const blockHeader = RustModule.SigmaRust.BlockHeader.from_json(headerJson);
console.log('pre-header');
const preHeader = RustModule.SigmaRust.PreHeader.from_block_header(blockHeader);
console.log('before signing');
const signedTx = RustModule.SigmaRust.Wallet
.from_secrets(wasmKeys)
.sign_transaction(
RustModule.SigmaRust.ErgoStateContext.dummy(), // TODO? Not implemented in sigma-rust
new RustModule.SigmaRust.ErgoStateContext(preHeader),
wasmTx,
txBoxesToSign,
RustModule.SigmaRust.ErgoBoxes.from_boxes_json([]), // TODO: not supported by sigma-rust
RustModule.SigmaRust.ErgoBoxes.from_boxes_json([]),
);
return signedTx.to_json();
}
Expand Down
4 changes: 2 additions & 2 deletions packages/yoroi-extension/package.json
Expand Up @@ -102,7 +102,7 @@
"crx": "5.0.1",
"css-loader": "5.0.2",
"cucumber": "git+https://github.com/SebastienGllmt/cucumber-js.git",
"ergo-lib-wasm-nodejs": "0.7.0",
"ergo-lib-wasm-nodejs": "0.10.0",
"eslint": "7.20.0",
"eslint-config-airbnb": "18.2.1",
"eslint-config-prettier": "7.2.0",
Expand Down Expand Up @@ -174,7 +174,7 @@
"crypto-browserify": "3.12.0",
"crypto-random-string": "3.3.1",
"dropbox": "4.0.30",
"ergo-lib-wasm-browser": "0.7.0",
"ergo-lib-wasm-browser": "0.10.0",
"es6-error": "4.1.1",
"file-saver": "2.0.5",
"jdenticon": "3.1.0",
Expand Down

0 comments on commit 98aeeb0

Please sign in to comment.