Skip to content

Commit 752afca

Browse files
committed
fix(api): guard shielded native calls
1 parent 6f9cfa6 commit 752afca

8 files changed

Lines changed: 553 additions & 17 deletions

File tree

‎chainbase/src/main/java/org/tron/common/zksnark/JLibrustzcash.java‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,9 @@ public class JLibrustzcash {
2929

3030
private static Librustzcash INSTANCE = LibrustzcashWrapper.getInstance();
3131

32-
public static void librustzcashZip32XskMaster(Zip32XskMasterParams params) {
32+
public static void librustzcashZip32XskMaster(Zip32XskMasterParams params)
33+
throws ZksnarkException {
34+
params.valid();
3335
INSTANCE.librustzcashZip32XskMaster(params.getData(), params.getSize(), params.getM_bytes());
3436
}
3537

@@ -38,11 +40,15 @@ public static void librustzcashInitZksnarkParams(InitZksnarkParams params) {
3840
params.getSpend_hash(), params.getOutput_path(), params.getOutput_hash());
3941
}
4042

41-
public static void librustzcashZip32XskDerive(Zip32XskDeriveParams params) {
43+
public static void librustzcashZip32XskDerive(Zip32XskDeriveParams params)
44+
throws ZksnarkException {
45+
params.valid();
4246
INSTANCE.librustzcashZip32XskDerive(params.getData(), params.getSize(), params.getM_bytes());
4347
}
4448

45-
public static boolean librustzcashZip32XfvkAddress(Zip32XfvkAddressParams params) {
49+
public static boolean librustzcashZip32XfvkAddress(Zip32XfvkAddressParams params)
50+
throws ZksnarkException {
51+
params.valid();
4652
return INSTANCE.librustzcashZip32XfvkAddress(params.getXfvk(), params.getJ(),
4753
params.getJ_ret(), params.getAddr_ret());
4854
}
@@ -118,7 +124,9 @@ public static boolean librustzcashCheckDiversifier(byte[] d) throws ZksnarkExcep
118124
return INSTANCE.librustzcashCheckDiversifier(d);
119125
}
120126

121-
public static boolean librustzcashSaplingSpendProof(SpendProofParams params) {
127+
public static boolean librustzcashSaplingSpendProof(SpendProofParams params)
128+
throws ZksnarkException {
129+
params.valid();
122130
return INSTANCE.librustzcashSaplingSpendProof(params.getCtx(), params.getAk(),
123131
params.getNsk(), params.getD(), params.getR(), params.getAlpha(), params.getValue(),
124132
params.getAnchor(), params.getVoucherPath(), params.getCv(), params.getRk(),

‎chainbase/src/main/java/org/tron/common/zksnark/LibrustzcashParam.java‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,24 @@ public static void valid32Params(byte[] value) throws ZksnarkException {
4141
validParamLength(value, 32);
4242
}
4343

44+
public static void validSpendAk(byte[] ak) throws ZksnarkException {
45+
valid32Params(ak);
46+
// Jubjub encodes y in little-endian order, with x's parity in the top bit of byte 31.
47+
// The identity (x = 0, y = 1) has canonical encoding 01 00 ... 00 00.
48+
// The current native decoder also accepts 01 00 ... 00 80: negating x = 0 still gives 0,
49+
// and it does not reject this non-canonical sign bit. Mask it to catch both encodings.
50+
// This only excludes the identity; native code still validates the point and subgroup.
51+
if (ak[0] != 1 || (ak[31] & 0x7f) != 0) {
52+
return;
53+
}
54+
for (int i = 1; i < 31; i++) {
55+
if (ak[i] != 0) {
56+
return;
57+
}
58+
}
59+
throw new ZksnarkException("Invalid spend ak: identity point");
60+
}
61+
4462
public static void validVoucherPath(byte[] voucherPath) throws ZksnarkException {
4563
validParamLength(voucherPath, 1 + 33 * 32 + 8);
4664
validByteValue(voucherPath[0], (byte) 0x20);
@@ -117,6 +135,9 @@ public Zip32XskMasterParams(byte[] data, int size, byte[] m_bytes) throws Zksnar
117135

118136
@Override
119137
public void valid() throws ZksnarkException {
138+
if (data == null || size < 0 || size > data.length) {
139+
throw new ZksnarkException("Invalid ZIP32 seed length");
140+
}
120141
validParamLength(m_bytes, 169);
121142
}
122143
}
@@ -129,7 +150,8 @@ public Zip32XskDeriveParams(byte[] data, int size, byte[] m_bytes) throws Zksnar
129150

130151
@Override
131152
public void valid() throws ZksnarkException {
132-
153+
validParamLength(getData(), 169);
154+
validParamLength(getM_bytes(), 169);
133155
}
134156
}
135157

@@ -159,7 +181,10 @@ public Zip32XfvkAddressParams(byte[] xfvk, byte[] j, byte[] j_ret, byte[] addr_r
159181

160182
@Override
161183
public void valid() throws ZksnarkException {
162-
184+
validParamLength(xfvk, 169);
185+
validParamLength(j, 11);
186+
validParamLength(j_ret, 11);
187+
validParamLength(addr_ret, 43);
163188
}
164189
}
165190

@@ -451,7 +476,7 @@ public static SpendProofParams decode(long ctx, byte[] data)
451476
@Override
452477
public void valid() throws ZksnarkException {
453478
validValueParams(value);
454-
valid32Params(ak);
479+
validSpendAk(ak);
455480
valid32Params(nsk);
456481
valid11Params(d);
457482
valid32Params(r);

‎framework/src/main/java/org/tron/core/Wallet.java‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2868,6 +2868,9 @@ public SpendResult isSpend(NoteParameters noteParameters) throws
28682868
note.getRcm().toByteArray());
28692869
byte[] nf = baseNote.nullifier(ak, nk, voucherContainer.position());
28702870

2871+
if (nf == null) {
2872+
throw new ZksnarkException("compute nullifier error");
2873+
}
28712874
if (chainBaseManager.getNullifierStore().has(nf)) {
28722875
result = SpendResult.newBuilder()
28732876
.setResult(true)
@@ -2893,7 +2896,9 @@ public BytesMessage createSpendAuthSig(SpendAuthSigParameters spendAuthSigParame
28932896
spendAuthSigParameters.getAlpha().toByteArray(),
28942897
spendAuthSigParameters.getTxHash().toByteArray(),
28952898
result);
2896-
JLibrustzcash.librustzcashSaplingSpendSig(spendSigParams);
2899+
if (!JLibrustzcash.librustzcashSaplingSpendSig(spendSigParams)) {
2900+
throw new ZksnarkException("Spend signature generation failed");
2901+
}
28972902

28982903
return BytesMessage.newBuilder().setValue(ByteString.copyFrom(result)).build();
28992904
}
@@ -2925,7 +2930,7 @@ public BytesMessage createShieldNullifier(NfParameters nfParameters) throws Zksn
29252930
incrementalMerkleVoucherContainer.position(),
29262931
result);
29272932
if (!JLibrustzcash.librustzcashComputeNf(computeNfParams)) {
2928-
return null;
2933+
throw new ZksnarkException("compute nullifier error");
29292934
}
29302935

29312936
return BytesMessage.newBuilder()

‎framework/src/main/java/org/tron/core/zen/ShieldedTRC20ParametersBuilder.java‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -222,11 +222,13 @@ private void createSpendAuth(byte[] dataToBeSigned) throws ZksnarkException {
222222
throw new ZksnarkException("missing expanded spending key for spend authorization");
223223
}
224224
byte[] result = new byte[64];
225-
JLibrustzcash.librustzcashSaplingSpendSig(
225+
if (!JLibrustzcash.librustzcashSaplingSpendSig(
226226
new LibrustzcashParam.SpendSigParams(spends.get(i).expsk.getAsk(),
227227
spends.get(i).alpha,
228228
dataToBeSigned,
229-
result));
229+
result))) {
230+
throw new ZksnarkException("Spend signature generation failed");
231+
}
230232
builder.getSpendDescriptionBuilder(i)
231233
.setSpendAuthoritySignature(ByteString.copyFrom(result));
232234
}
@@ -354,12 +356,14 @@ public ShieldedTRC20Parameters build(boolean withAsk) throws ZksnarkException {
354356
builder.setMessageHash(ByteString.copyFrom(dataHashToBeSigned));
355357

356358
byte[] bindingSig = new byte[64];
357-
JLibrustzcash.librustzcashSaplingBindingSig(
359+
if (!JLibrustzcash.librustzcashSaplingBindingSig(
358360
new LibrustzcashParam.BindingSigParams(ctx,
359361
valueBalance,
360362
dataHashToBeSigned,
361363
bindingSig)
362-
);
364+
)) {
365+
throw new ZksnarkException("Binding signature generation failed");
366+
}
363367
builder.setBindingSignature(ByteString.copyFrom(bindingSig));
364368
} catch (Exception e) {
365369
throw new ZksnarkException("build the shielded TRC-20 parameters error: " + e.getMessage());

‎framework/src/main/java/org/tron/core/zen/ZenTransactionBuilder.java‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -170,12 +170,14 @@ public TransactionCapsule build(boolean withAsk) throws ZksnarkException {
170170
}
171171

172172
byte[] bindingSig = new byte[64];
173-
JLibrustzcash.librustzcashSaplingBindingSig(
173+
if (!JLibrustzcash.librustzcashSaplingBindingSig(
174174
new BindingSigParams(ctx,
175175
valueBalance,
176176
dataHashToBeSigned,
177177
bindingSig)
178-
);
178+
)) {
179+
throw new ZksnarkException("Binding signature generation failed");
180+
}
179181
contractBuilder.setBindingSignature(ByteString.copyFrom(bindingSig));
180182
} catch (ZksnarkException e) {
181183
throw e;
@@ -197,11 +199,13 @@ public TransactionCapsule build(boolean withAsk) throws ZksnarkException {
197199
public void createSpendAuth(byte[] dataToBeSigned) throws ZksnarkException {
198200
for (int i = 0; i < spends.size(); i++) {
199201
byte[] result = new byte[64];
200-
JLibrustzcash.librustzcashSaplingSpendSig(
202+
if (!JLibrustzcash.librustzcashSaplingSpendSig(
201203
new SpendSigParams(spends.get(i).expsk.getAsk(),
202204
spends.get(i).alpha,
203205
dataToBeSigned,
204-
result));
206+
result))) {
207+
throw new ZksnarkException("Spend signature generation failed");
208+
}
205209
contractBuilder.getSpendDescriptionBuilder(i)
206210
.setSpendAuthoritySignature(ByteString.copyFrom(result));
207211
}
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
package org.tron.common.zksnark;
2+
3+
import static org.junit.Assert.assertEquals;
4+
import static org.junit.Assert.assertThrows;
5+
import static org.junit.Assert.assertTrue;
6+
import static org.mockito.ArgumentMatchers.any;
7+
import static org.mockito.Mockito.mock;
8+
import static org.mockito.Mockito.verify;
9+
import static org.mockito.Mockito.verifyNoInteractions;
10+
import static org.mockito.Mockito.when;
11+
12+
import java.util.Arrays;
13+
import org.bouncycastle.util.encoders.Hex;
14+
import org.junit.After;
15+
import org.junit.Before;
16+
import org.junit.Test;
17+
import org.springframework.test.util.ReflectionTestUtils;
18+
import org.tron.common.zksnark.LibrustzcashParam.SpendProofParams;
19+
import org.tron.common.zksnark.LibrustzcashParam.Zip32XfvkAddressParams;
20+
import org.tron.common.zksnark.LibrustzcashParam.Zip32XskDeriveParams;
21+
import org.tron.common.zksnark.LibrustzcashParam.Zip32XskMasterParams;
22+
import org.tron.core.exception.ZksnarkException;
23+
24+
public class ShieldedNativeValidationTest {
25+
26+
private Librustzcash original;
27+
private Librustzcash nativeApi;
28+
29+
@Before
30+
public void setUp() {
31+
original = (Librustzcash) ReflectionTestUtils.getField(JLibrustzcash.class, "INSTANCE");
32+
nativeApi = mock(Librustzcash.class);
33+
ReflectionTestUtils.setField(JLibrustzcash.class, "INSTANCE", nativeApi);
34+
}
35+
36+
@After
37+
public void tearDown() {
38+
ReflectionTestUtils.setField(JLibrustzcash.class, "INSTANCE", original);
39+
}
40+
41+
private static byte[] validAk() {
42+
return Hex.decode("db8c9492f599646369a4855b4260fe3b957cec8e1c33de7036ec61d8059d52d1");
43+
}
44+
45+
private static byte[] identity(boolean sign) {
46+
byte[] ak = new byte[32];
47+
ak[0] = 1;
48+
ak[31] = sign ? (byte) 0x80 : 0;
49+
return ak;
50+
}
51+
52+
private static SpendProofParams spend(byte[] ak) throws ZksnarkException {
53+
byte[] path = new byte[1065];
54+
path[0] = 32;
55+
for (int i = 0; i < 32; i++) {
56+
path[1 + i * 33] = 32;
57+
}
58+
return new SpendProofParams(1, ak, new byte[32], new byte[11], new byte[32],
59+
new byte[32], 0, new byte[32], path, new byte[32], new byte[32], new byte[192]);
60+
}
61+
62+
@Test
63+
public void rejectsBothIdentityEncodingsBeforeNativeProof() {
64+
for (boolean sign : new boolean[]{false, true}) {
65+
ZksnarkException error = assertThrows(ZksnarkException.class,
66+
() -> spend(identity(sign)));
67+
assertEquals("Invalid spend ak: identity point", error.getMessage());
68+
}
69+
verifyNoInteractions(nativeApi);
70+
}
71+
72+
@Test
73+
public void rejectsInvalidAkLengths() {
74+
for (byte[] ak : new byte[][]{null, new byte[0], new byte[31], new byte[33]}) {
75+
assertThrows(ZksnarkException.class, () -> spend(ak));
76+
}
77+
verifyNoInteractions(nativeApi);
78+
}
79+
80+
@Test
81+
public void revalidatesSetterAndArrayMutationsAtNativeBoundary() throws Exception {
82+
SpendProofParams params = spend(validAk());
83+
params.setAk(identity(true));
84+
assertThrows(ZksnarkException.class,
85+
() -> JLibrustzcash.librustzcashSaplingSpendProof(params));
86+
87+
byte[] ak = validAk();
88+
SpendProofParams aliased = spend(ak);
89+
System.arraycopy(identity(false), 0, ak, 0, ak.length);
90+
assertThrows(ZksnarkException.class,
91+
() -> JLibrustzcash.librustzcashSaplingSpendProof(aliased));
92+
verifyNoInteractions(nativeApi);
93+
}
94+
95+
@Test
96+
public void rejectsIdentityDerivedFromZeroAsk() {
97+
byte[] ak = new byte[32];
98+
original.librustzcashAskToAk(new byte[32], ak);
99+
assertThrows(ZksnarkException.class, () -> spend(ak));
100+
verifyNoInteractions(nativeApi);
101+
}
102+
103+
@Test
104+
public void acceptsNormalAkWithSignBitAndPreservesNativeFailure() throws Exception {
105+
SpendProofParams params = spend(validAk());
106+
when(nativeApi.librustzcashSaplingSpendProof(
107+
org.mockito.ArgumentMatchers.anyLong(), any(), any(), any(), any(), any(),
108+
org.mockito.ArgumentMatchers.anyLong(), any(), any(), any(), any(), any()))
109+
.thenReturn(true, false);
110+
assertTrue(JLibrustzcash.librustzcashSaplingSpendProof(params));
111+
org.junit.Assert.assertFalse(JLibrustzcash.librustzcashSaplingSpendProof(params));
112+
org.junit.Assert.assertArrayEquals(validAk(), params.getAk());
113+
}
114+
115+
@Test
116+
public void validatesZip32MasterSeedBoundsAndRechecksMutation() throws Exception {
117+
assertThrows(ZksnarkException.class,
118+
() -> new Zip32XskMasterParams(null, 0, new byte[169]));
119+
assertThrows(ZksnarkException.class,
120+
() -> new Zip32XskMasterParams(new byte[32], -1, new byte[169]));
121+
assertThrows(ZksnarkException.class,
122+
() -> new Zip32XskMasterParams(new byte[32], 33, new byte[169]));
123+
Zip32XskMasterParams params = new Zip32XskMasterParams(new byte[32], 32, new byte[169]);
124+
params.setSize(33);
125+
assertThrows(ZksnarkException.class,
126+
() -> JLibrustzcash.librustzcashZip32XskMaster(params));
127+
verifyNoInteractions(nativeApi);
128+
}
129+
130+
@Test
131+
public void preservesEmptyAndPrefixSeedsAndHardenedChildIndices() throws Exception {
132+
byte[] output = new byte[169];
133+
byte[] seed = new byte[32];
134+
JLibrustzcash.librustzcashZip32XskMaster(new Zip32XskMasterParams(seed, 16, output));
135+
verify(nativeApi).librustzcashZip32XskMaster(seed, 16, output);
136+
byte[] emptySeed = new byte[0];
137+
JLibrustzcash.librustzcashZip32XskMaster(new Zip32XskMasterParams(emptySeed, 0, output));
138+
verify(nativeApi).librustzcashZip32XskMaster(emptySeed, 0, output);
139+
byte[] parent = new byte[169];
140+
JLibrustzcash.librustzcashZip32XskDerive(
141+
new Zip32XskDeriveParams(parent, Integer.MIN_VALUE, output));
142+
verify(nativeApi).librustzcashZip32XskDerive(parent, Integer.MIN_VALUE, output);
143+
}
144+
145+
@Test
146+
public void rejectsShortZip32KeysAndOutputBuffers() throws Exception {
147+
assertThrows(ZksnarkException.class,
148+
() -> new Zip32XskDeriveParams(new byte[168], 0, new byte[169]));
149+
assertThrows(ZksnarkException.class,
150+
() -> new Zip32XskDeriveParams(new byte[169], 0, new byte[168]));
151+
for (int field = 0; field < 4; field++) {
152+
byte[][] arrays = {new byte[169], new byte[11], new byte[11], new byte[43]};
153+
arrays[field] = Arrays.copyOf(arrays[field], arrays[field].length - 1);
154+
assertThrows(ZksnarkException.class,
155+
() -> new Zip32XfvkAddressParams(arrays[0], arrays[1], arrays[2], arrays[3]));
156+
}
157+
Zip32XskDeriveParams derive = new Zip32XskDeriveParams(new byte[169], 0, new byte[169]);
158+
derive.setData(new byte[1]);
159+
assertThrows(ZksnarkException.class,
160+
() -> JLibrustzcash.librustzcashZip32XskDerive(derive));
161+
Zip32XfvkAddressParams address =
162+
new Zip32XfvkAddressParams(new byte[169], new byte[11], new byte[11], new byte[43]);
163+
address.setAddr_ret(new byte[1]);
164+
assertThrows(ZksnarkException.class,
165+
() -> JLibrustzcash.librustzcashZip32XfvkAddress(address));
166+
verifyNoInteractions(nativeApi);
167+
}
168+
}

0 commit comments

Comments
 (0)