-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsign-auth-entry.ts
66 lines (58 loc) · 1.68 KB
/
sign-auth-entry.ts
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
import {
Address,
StrKey,
xdr,
nativeToScVal,
Keypair,
hash,
} from "@stellar/stellar-sdk";
// This can be replaced with the same helper in the sdk when it lands
// https://github.com/stellar/js-stellar-base/pull/678
export async function authorizeEntry(
entry: xdr.SorobanAuthorizationEntry,
signer: (input: Buffer) => Promise<Buffer>,
validUntilLedgerSeq: any,
networkPassphrase: string,
) {
// no-op
if (
entry.credentials().switch() !==
xdr.SorobanCredentialsType.sorobanCredentialsAddress()
) {
return entry;
}
const addrAuth = entry.credentials().address();
addrAuth.signatureExpirationLedger(validUntilLedgerSeq);
const networkId = hash(Buffer.from(networkPassphrase));
const preimage = xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(
new xdr.HashIdPreimageSorobanAuthorization({
networkId,
nonce: addrAuth.nonce(),
invocation: entry.rootInvocation(),
signatureExpirationLedger: addrAuth.signatureExpirationLedger(),
}),
);
const signature = await signer(preimage.toXDR());
const publicKey = Address.fromScAddress(addrAuth.address()).toString();
if (
!Keypair.fromPublicKey(publicKey).verify(hash(preimage.toXDR()), signature)
) {
throw new Error(`signature doesn't match payload`);
}
const sigScVal = nativeToScVal(
{
public_key: StrKey.decodeEd25519PublicKey(publicKey),
signature,
},
{
// force the keys to be interpreted as symbols (expected for
// Soroban [contracttype]s)
type: {
public_key: ["symbol", null],
signature: ["symbol", null],
} as any,
},
);
addrAuth.signature(xdr.ScVal.scvVec([sigScVal]));
return entry;
}