Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CIP30 signData implementation #2782

Merged
merged 2 commits into from
May 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/yoroi-ergo-connector/example-cardano/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ <h1 class="display-4 text-center">Cardano dApp Example</h1>
<div class="col-6 mb-4">
<button id="get-collateral-utxos" class="btn btn-light w-100">Get collateral UTXOS</button>
</div>
<div class="col-6 mb-4">
<input class="w-40" type="text" value="sign me" id="sign-data-payload" />
<button id="sign-data" class="btn btn-light w-50">Sign data</button>
</div>
<div class="col-6 mb-4">
<a href="/subpage.html">Go to a subpage</a>
</div>
Expand Down
41 changes: 40 additions & 1 deletion packages/yoroi-ergo-connector/example-cardano/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const submitTx = document.querySelector('#submit-tx')
const signTx = document.querySelector('#sign-tx')
const createTx = document.querySelector('#create-tx')
const getCollateralUtxos = document.querySelector('#get-collateral-utxos')
const signData = document.querySelector('#sign-data')
const alertEl = document.querySelector('#alert')
const spinner = document.querySelector('#spinner')

Expand All @@ -30,6 +31,7 @@ let cardanoApi
let returnType = 'cbor'
let utxos
let usedAddresses
let unusedAddresses
let changeAddress
let unsignedTransactionHex
let transactionHex
Expand Down Expand Up @@ -211,6 +213,7 @@ getUnUsedAddresses.addEventListener('click', () => {
return;
}
addresses = addressesFromCborIfNeeded(addresses)
unusedAddresses = addresses
alertSuccess(`Address: `)
alertEl.innerHTML = '<h2>Unused addresses:</h2><pre>' + JSON.stringify(addresses, undefined, 2) + '</pre>'
});
Expand Down Expand Up @@ -626,11 +629,12 @@ createTx.addEventListener('click', () => {

getCollateralUtxos.addEventListener('click', () => {
toggleSpinner('show');

if (!accessGranted) {
alertError('Should request access first');
return;
}

const amount = '4900000';
cardanoApi.getCollateralUtxos(
Buffer.from(
Expand All @@ -649,6 +653,41 @@ getCollateralUtxos.addEventListener('click', () => {
})
})

signData.addEventListener('click', () => {
toggleSpinner('show');

if (!accessGranted) {
alertError('Should request access first');
return;
}

let address;
if (usedAddresses && usedAddresses.length > 0) {
address = usedAddresses[0];
} else if (unusedAddresses && unusedAddresses.length > 0) {
address = unusedAddresses[0];
} else {
alertError('Should request used or unused addresses first');
return;
}

const payload = document.querySelector('#sign-data-payload').value;
let payloadHex;
if (payload.startsWith('0x')) {
payloadHex = Buffer.from(payload.replace('^0x', ''), 'hex').toString('hex');
} else {
payloadHex = Buffer.from(payload, 'utf8').toString('hex');
}
cardanoApi.signData(address, payloadHex).then(sig => {
alertSuccess('Signature:' + JSON.stringify(sig))
}).catch(error => {
console.error(error);
alertError(error.info);
}).then(() => {
toggleSpinner('hide');
});
});

function alertError (text) {
toggleSpinner('hide');
alertEl.className = 'alert alert-danger'
Expand Down
5 changes: 2 additions & 3 deletions packages/yoroi-ergo-connector/src/inject.js
Original file line number Diff line number Diff line change
Expand Up @@ -254,9 +254,8 @@ class CardanoAPI {
return this._cardano_rpc_call('sign_tx/cardano', [{ tx, partialSign, returnTx }]);
}

signData(address, sigStructure) {
// TODO
throw new Error('Not implemented yet');
signData(address, payload) {
return this._cardano_rpc_call("sign_data", [address, payload]);
}

getCollateralUtxos(requiredAmount) {
Expand Down
12 changes: 5 additions & 7 deletions packages/yoroi-extension/app/ergo-connector/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ export const createAuthEntry: ({|
stakingKey.to_public().hash()
)
).to_address();
const entropy = await cip8Sign(
const entropy = (await cip8Sign(
Buffer.from(address.to_bytes()),
derivedSignKey,
Buffer.from(`DAPP_LOGIN: ${appAuthID}`, 'utf8'),
);
)).signature();

const appPrivKey = RustModule.WalletV4.Bip32PrivateKey.from_bip39_entropy(
entropy,
Expand All @@ -72,12 +72,11 @@ export const authSignHexPayload: ({|
return appPrivKey.sign(Buffer.from(payloadHex, 'hex')).to_hex();
}

// return the hex string representation of the COSESign1
const cip8Sign = async (
export const cip8Sign = async (
address: Buffer,
signKey: RustModule.WalletV4.PrivateKey,
payload: Buffer,
): Promise<Buffer> => {
): Promise<RustModule.MessageSigning.COSESign1> => {
const protectedHeader = RustModule.MessageSigning.HeaderMap.new();
protectedHeader.set_algorithm_id(
RustModule.MessageSigning.Label.from_algorithm_id(
Expand All @@ -94,6 +93,5 @@ const cip8Sign = async (
const builder = RustModule.MessageSigning.COSESign1Builder.new(headers, payload, false);
const toSign = builder.make_data_to_sign().to_bytes();
const signedSigStruct = signKey.sign(toSign).to_bytes();
const coseSign1 = builder.build(signedSigStruct);
return Buffer.from(coseSign1.signature());
return builder.build(signedSigStruct);
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ import { LoadingButton } from '@mui/lab';
import NoDappIcon from '../../../assets/images/dapp-connector/no-dapp.inline.svg';

type Props = {|
+txData: CardanoConnectorSignRequest,
+txData: ?CardanoConnectorSignRequest,
+onCopyAddressTooltip: (string, string) => void,
+onCancel: () => void,
+onConfirm: string => Promise<void>,
Expand All @@ -66,6 +66,7 @@ type Props = {|
+connectedWebsite: ?WhitelistEntry,
+isReorg: boolean,
+submissionError: ?SignSubmissionErrorType,
+signData: ?{| address: string, payload: string |},
|};

const messages = defineMessages({
Expand Down Expand Up @@ -298,6 +299,14 @@ class SignTxPage extends Component<Props, State> {
);
};

renderPayload(payloadHex: string): string {
const utf8 = Buffer.from(payloadHex, 'hex').toString('utf8');
if (utf8.match(/^[\P{C}\t\r\n]+$/u)) {
return utf8;
}
return payloadHex;
}

render(): Node {
const { form } = this;
const walletPasswordField = form.$('walletPassword');
Expand All @@ -309,17 +318,119 @@ class SignTxPage extends Component<Props, State> {
connectedWebsite,
isReorg,
submissionError,
signData,
} = this.props;

const { isSubmitting } = this.state;

const url = connectedWebsite?.url ?? '';
const faviconUrl = connectedWebsite?.image ?? '';

const txAmountDefaultToken = txData.amount.defaults.defaultIdentifier;
const txAmount = txData.amount.get(txAmountDefaultToken) ?? new BigNumber('0');
const txFeeAmount = new BigNumber(txData.fee.amount).negated();
const txTotalAmount = txAmount.plus(txFeeAmount);
let content;
let utxosContent;
if (txData) {
// signing a tx
const txAmountDefaultToken = txData.amount.defaults.defaultIdentifier;
const txAmount = txData.amount.get(txAmountDefaultToken) ?? new BigNumber('0');
const txFeeAmount = new BigNumber(txData.fee.amount).negated();
const txTotalAmount = txAmount.plus(txFeeAmount);
content = (
<Box pt="32px">
<Typography color="var(--yoroi-palette-gray-900)" variant="h5" marginBottom="8px">
{intl.formatMessage(signTxMessages.totals)}
</Typography>
<Box
width="100%"
px="12px"
py="20px"
pb="12px"
border="1px solid var(--yoroi-palette-gray-100)"
borderRadius="6px"
>
<Box
display="flex"
justifyContent="space-between"
alignItems="center"
color="var(--yoroi-palette-gray-600)"
py="6px"
px="10px"
>
<Typography>{intl.formatMessage(signTxMessages.transactionFee)}</Typography>
<Typography>
{this.renderAmountDisplay({
entry: {
identifier: txData.fee.tokenId,
networkId: txData.fee.networkId,
amount: txFeeAmount,
},
})}
</Typography>
</Box>
<Box
px="12px"
py="23px"
mt="10px"
display="flex"
justifyContent="space-between"
alignItems="center"
borderRadius="6px"
backgroundColor="var(--yoroi-palette-primary-300)"
color="var(--yoroi-palette-common-white)"
>
<Typography>{intl.formatMessage(signTxMessages.totalAmount)}</Typography>
<Typography variant="h3">
{this.renderAmountDisplay({
entry: {
identifier: txAmountDefaultToken,
networkId: txData.amount.defaults.defaultNetworkId,
amount: txTotalAmount,
},
})}
</Typography>
</Box>
</Box>
</Box>
);
utxosContent = (
<Box>
<CardanoUtxoDetails
txData={txData}
onCopyAddressTooltip={this.props.onCopyAddressTooltip}
addressToDisplayString={this.props.addressToDisplayString}
getCurrentPrice={this.props.getCurrentPrice}
getTokenInfo={this.props.getTokenInfo}
notification={this.props.notification}
selectedExplorer={this.props.selectedExplorer}
unitOfAccountSetting={this.props.unitOfAccountSetting}
/>
</Box>
);
} else if (signData) {
// signing data
content = (
<Box pt="32px">
<Typography color="var(--yoroi-palette-gray-900)" variant="h5" marginBottom="8px">
{intl.formatMessage(signTxMessages.signMessage)}
</Typography>
<Box
width="100%"
px="12px"
py="20px"
pb="12px"
border="1px solid var(--yoroi-palette-gray-100)"
borderRadius="6px"
>
<pre>
{this.renderPayload(signData.payload)}
</pre>
</Box>
</Box>
);
utxosContent = null;
} else {
return null;
}

return (
<SignTxTabs
overviewContent={
Expand Down Expand Up @@ -384,62 +495,7 @@ class SignTxPage extends Component<Props, State> {
getTokenInfo={this.props.getTokenInfo}
/>
</Box>
<Box pt="32px">
<Typography color="var(--yoroi-palette-gray-900)" variant="h5" marginBottom="8px">
{intl.formatMessage(signTxMessages.totals)}
</Typography>
<Box
width="100%"
px="12px"
py="20px"
pb="12px"
border="1px solid var(--yoroi-palette-gray-100)"
borderRadius="6px"
>
<Box
display="flex"
justifyContent="space-between"
alignItems="center"
color="var(--yoroi-palette-gray-600)"
py="6px"
px="10px"
>
<Typography>{intl.formatMessage(signTxMessages.transactionFee)}</Typography>
<Typography>
{this.renderAmountDisplay({
entry: {
identifier: txData.fee.tokenId,
networkId: txData.fee.networkId,
amount: txFeeAmount,
},
})}
</Typography>
</Box>
<Box
px="12px"
py="23px"
mt="10px"
display="flex"
justifyContent="space-between"
alignItems="center"
borderRadius="6px"
backgroundColor="var(--yoroi-palette-primary-300)"
color="var(--yoroi-palette-common-white)"
>
<Typography>{intl.formatMessage(signTxMessages.totalAmount)}</Typography>
<Typography variant="h3">
{this.renderAmountDisplay({
entry: {
identifier: txAmountDefaultToken,
networkId: txData.amount.defaults.defaultNetworkId,
amount: txTotalAmount,
},
})}
</Typography>
</Box>
</Box>
</Box>

{content}
<Box mt="46px">
<TextField
type="password"
Expand Down Expand Up @@ -474,20 +530,7 @@ class SignTxPage extends Component<Props, State> {
</Box>
</Box>
}
utxoAddressContent={
<Box>
<CardanoUtxoDetails
txData={txData}
onCopyAddressTooltip={this.props.onCopyAddressTooltip}
addressToDisplayString={this.props.addressToDisplayString}
getCurrentPrice={this.props.getCurrentPrice}
getTokenInfo={this.props.getTokenInfo}
notification={this.props.notification}
selectedExplorer={this.props.selectedExplorer}
unitOfAccountSetting={this.props.unitOfAccountSetting}
/>
</Box>
}
utxoAddressContent={utxosContent}
/>
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ export const signTxMessages: Object = defineMessages({
id: 'api.errors.IncorrectPasswordError',
defaultMessage: '!!!Incorrect wallet password.',
},
signMessage: {
id: 'connector.signin.signMessage',
defaultMessage: '!!!Sign Message',
},
});

type State = {|
Expand Down
Loading