-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bitcoin.java~
322 lines (288 loc) · 11.7 KB
/
Bitcoin.java~
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class Bitcoin {
//private static Map<String,Transaction> transactions;
private static Map<String,Map<Integer,TransactionOutput>> transactions2;
private static byte[] binaryData;
private static int invalidTransactions;
private static Cipher aes;
private static int validTransactions;
private static List<byte[]> transactionList;
private static String identity = "-----BEGIN RSA PUBLIC KEY-----"+
"MIGJAoGBAN3MxXHcbc1VNKTOgdm7W+i/dVnjv8vYGlbkdaTKzYgi8rQm126Sri87"+
"702UBNzmkkZyKbRKL/Bfc4EG8/Mt9Pd2xQlRyXCL9FnIFWHyhfIQtW+oBsGI5UhG"+
"I8B8MiPOMfb6d/PdK+vd4riUxHAvCkHW5Lw0szAD1RVGbkG/7qnzAgMBAAE="+
"-----END RSA PUBLIC KEY-----";
private static String identityBytes = "1f5a0200bc94ae4264642855786d9c2bb436b9e129ef95e6416136c03f339581";
public static void main(String[] args) throws IOException, InvalidKeyException {
binaryData = null;
invalidTransactions = 0;
validTransactions = 0;
transactions2 = new HashMap<String,Map<Integer,TransactionOutput>>();
transactionList = new ArrayList<byte[]>();
try {
Path path = Paths.get("./src/transactionData-10000-3.bin");
binaryData = Files.readAllBytes(path);
System.out.println(binaryData.length);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
aes = Cipher.getInstance("RSA/ECB/PKCS1Padding");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
parseGenesis();
System.out.println();
ByteBuffer numTransactionsBB = ByteBuffer.allocate(4);
numTransactionsBB.order(ByteOrder.LITTLE_ENDIAN);
numTransactionsBB.put(binaryData,126,4);
int numTransactions = numTransactionsBB.getInt(0);
System.out.println("numTransactions: " + numTransactions+"\n");
int currentIndex = 130;
for(int i = 0; i < numTransactions; i++) {
System.out.println(i+1);
currentIndex = processTransaction(currentIndex);
}
System.out.println(invalidTransactions);
System.out.println(validTransactions);
System.out.println(dHash(identity.getBytes()));
System.out.println(identity.getBytes().length);
}
public static int processTransaction(int startIndex) throws IOException, InvalidKeyException {
boolean valid = true;
Map<String,Set<Integer>> changedMap = new HashMap<String,Set<Integer>>();
Map<String,String> signatureMap = new HashMap<String,String>();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int currentIndex = startIndex;
ByteBuffer numInputsBB = ByteBuffer.allocate(2);
numInputsBB.order(ByteOrder.LITTLE_ENDIAN);
numInputsBB.put(binaryData,currentIndex,2);
int inputs = numInputsBB.getShort(0);
System.out.println("Num Inputs: " + inputs);
currentIndex += 2;
int totalInputValue = 0;
outputStream.write(getBytes(binaryData,0,2));
for(int i = 0; i < inputs; i++) {
int inputStart=currentIndex;
System.out.println("Input:" + i+1);
byte[] prevTransBytes = getBytes(binaryData,currentIndex,currentIndex+32);
currentIndex +=32;
String s1 = bytesToHex(prevTransBytes);
System.out.println("Prev Trans Hash : " + s1);
ByteBuffer indexBB = ByteBuffer.allocate(2);
indexBB.order(ByteOrder.LITTLE_ENDIAN);
indexBB.put(binaryData,currentIndex,2);
int index = indexBB.getShort(0);
System.out.println("Prev Trans index: " + index);
currentIndex += 2;
int signatureStart = currentIndex;
String signature = bytesToHex(getBytes(binaryData,currentIndex,currentIndex+128));
currentIndex += 128;
int signatureEnd = currentIndex;
ByteBuffer lengthBB = ByteBuffer.allocate(2);
lengthBB.order(ByteOrder.LITTLE_ENDIAN);
lengthBB.put(binaryData,currentIndex,2);
int length = lengthBB.getShort(0);
System.out.println("Public key length: " + length);
currentIndex+=2;
byte[] inputKey = getBytes(binaryData,currentIndex,currentIndex+length);
currentIndex+=length;
int inputEnd = currentIndex;
outputStream.write(getBytes(binaryData,inputStart,signatureStart));
outputStream.write(getBytes(binaryData,signatureEnd,inputEnd));
if(transactions2.containsKey(s1)) {
//Transaction prev = transactions.get(s1);
//Map<Integer,TransactionOutput> outputs = prev.getOutputMap();
Map<Integer,TransactionOutput> outputs2 = transactions2.get(s1);
if(!changedMap.containsKey(s1)) {
changedMap.put(s1,new HashSet<Integer>());
}
if(outputs2.containsKey(index)) {
TransactionOutput output = outputs2.get(index);
if(!output.isUsed()) {
String hashedInputKey = dHash(inputKey);
if(hashedInputKey.equals(output.getKey())) {
signatureMap.put(output.getKey(),signature);
changedMap.get(s1).add(index);
int value = output.getValue();
totalInputValue += value;
} else {
System.out.println("Transaction invalid: Hashed input key does not equal hashed output key");
valid = false;
}
} else {
System.out.println("Transaction invalid: Output already used before, write code to deal with this");
valid = false;
}
} else {
System.out.println("Transaction invalid: Index not found in transaction's output map, write code to deal with this");
valid = false;
}
} else {
System.out.println("Transaction invalid: Key not found, write code to deal with this");
valid = false;
}
}
int outputStart = currentIndex;
ByteBuffer numOutputsBB = ByteBuffer.allocate(2);
numOutputsBB.order(ByteOrder.LITTLE_ENDIAN);
numOutputsBB.put(binaryData,currentIndex,2);
int outputs = numOutputsBB.getShort(0);
System.out.println("Num Outputs: " + outputs);
currentIndex += 2;
int totalOutputValue = 0;
Map<Integer,TransactionOutput> outputMap = new HashMap<Integer,TransactionOutput>();
for(int i = 0; i < outputs; i++) {
ByteBuffer outputValueBB = ByteBuffer.allocate(4);
outputValueBB.order(ByteOrder.LITTLE_ENDIAN);
outputValueBB.put(binaryData,currentIndex,4);
int outputValue = outputValueBB.getInt(0);
System.out.println("Output Value: " + outputValue);
currentIndex += 4;
totalOutputValue += outputValue;
byte[] hashedPublicKeyBytes = getBytes(binaryData,currentIndex,currentIndex+32);
currentIndex +=32;
String s1 = bytesToHex(hashedPublicKeyBytes);
TransactionOutput output = new TransactionOutput(outputValue,s1);
outputMap.put(i,output);
}
System.out.println(" Total Input Value: " + totalInputValue + " Total output value: " + totalOutputValue);
if(totalOutputValue > totalInputValue) {
System.out.println("Transaction invalid: Output value > input value, write code to deal with this");
valid = false;
}
outputStream.write(getBytes(binaryData,outputStart,currentIndex));
String transactionHash = dHash(getBytes(binaryData,startIndex,currentIndex));
Transaction current = new Transaction(transactionHash);
current.setOutputMap(outputMap);
//transactions.put(transactionHash,current);
if(valid) {
byte[] transactionBytes = outputStream.toByteArray();
String newHash = dHash(transactionBytes);
for(String key: signatureMap.keySet()) {
String signature = signatureMap.get(key);
byte[] keyBytes = key.getBytes();
SecretKeySpec privateKey = new SecretKeySpec(keyBytes, "RSA/ECB/PKCS1Padding");
aes.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] encrypted= new byte[aes.getOutputSize(128)];
String newSignature = bytesToHex(encrypted);
System.out.println(newSignature);
System.out.println(signature);
}
validTransactions++;
transactionList.add(getBytes(binaryData,startIndex,currentIndex));
transactions2.put(transactionHash, outputMap);
for(String s: changedMap.keySet()) {
Set<Integer> indexSet = changedMap.get(s);
for(Integer i: indexSet) {
transactions2.get(s).get(i).setUsed(true);
}
}
} else {
invalidTransactions++;
}
return currentIndex;
}
public static String dHash(byte[] bytes) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
md.update(bytes);
byte[] byteArray = md.digest();
md.update(byteArray);
byteArray = md.digest();
StringBuffer result = new StringBuffer();
for (byte b:byteArray) {
result.append(String.format("%02x", b));
}
return result.toString();
}
public static void parseGenesis() {
ByteBuffer versionBB = ByteBuffer.allocate(4);
versionBB.order(ByteOrder.LITTLE_ENDIAN);
versionBB.put(binaryData, 0, 4);
System.out.println("Version: " + versionBB.getInt(0));
byte[] prevBlockBytes = getBytes(binaryData,4,36);
String s1 = bytesToHex(prevBlockBytes);
System.out.println("Prev Block Hash : " + s1);
byte[] merkleBytes = getBytes(binaryData,36,68);
String s2 = bytesToHex(merkleBytes);
System.out.println("Merkle : " + s2);
ByteBuffer creationTimeBB = ByteBuffer.allocate(4);
creationTimeBB.order(ByteOrder.LITTLE_ENDIAN);
creationTimeBB.put(binaryData,68,4);
System.out.println("Creation Time: " + creationTimeBB.getInt(0));
ByteBuffer difficultyBB = ByteBuffer.allocate(2);
difficultyBB.order(ByteOrder.LITTLE_ENDIAN);
difficultyBB.put(binaryData,72,2);
System.out.println("Difficulty: " + difficultyBB.getShort(0));
ByteBuffer nonceBB = ByteBuffer.allocate(8);
nonceBB.order(ByteOrder.LITTLE_ENDIAN);
nonceBB.put(binaryData,74,8);
System.out.println("Nonce: " + nonceBB.getLong(0));
ByteBuffer numTransactionsTimeBB = ByteBuffer.allocate(4);
numTransactionsTimeBB.order(ByteOrder.LITTLE_ENDIAN);
numTransactionsTimeBB.put(binaryData,82,4);
System.out.println("\nnumTransactions: " + numTransactionsTimeBB.getInt(0));
ByteBuffer numInputsBB = ByteBuffer.allocate(2);
numInputsBB.order(ByteOrder.LITTLE_ENDIAN);
numInputsBB.put(binaryData,86,2);
System.out.println("numInputs: " + numInputsBB.getShort(0));
ByteBuffer numOutputsBB = ByteBuffer.allocate(2);
numOutputsBB.order(ByteOrder.LITTLE_ENDIAN);
numOutputsBB.put(binaryData,88,2);
System.out.println("numOutputs: " + numOutputsBB.getShort(0));
ByteBuffer valueBB = ByteBuffer.allocate(4);
valueBB.order(ByteOrder.LITTLE_ENDIAN);
valueBB.put(binaryData,90,4);
System.out.println("Value: " + valueBB.getInt(0));
byte[] hashedPublicKeyBytes = getBytes(binaryData,94,126);
String s3 = bytesToHex(hashedPublicKeyBytes);
System.out.println("Hashed Public Key : " + s3);
TransactionOutput genesisOutput = new TransactionOutput(valueBB.getInt(0),s3);
Transaction genesis = new Transaction(s2);
Map<Integer,TransactionOutput> genesisOutputMap = genesis.getOutputMap();
genesisOutputMap.put(0, genesisOutput);
//transactions.put(s2,genesis);
transactions2.put(s2,genesisOutputMap);
transactionList.add(getBytes(binaryData,0,126));
}
public static String bytesToHex(byte[] in) {
final StringBuilder builder = new StringBuilder();
for(byte b : in) {
builder.append(String.format("%02x", b));
}
return builder.toString();
}
private static byte[] getBytes(byte[] src, int start, int end) {
byte[] bb = new byte[end - start];
System.arraycopy(src, start, bb, 0, end - start);
return bb;
}
}