CO3326 Computer security
Coursework assignment 1 2019–20

Important

Students have been allocated a unique cryptocurrency wallet and initial blockchain with a genesis block to use for this coursework assignment. You can obtain this using your Student Reference Number (SRN) from the following URL: http://foley.gold.ac.uk/cw20/api/cw1/{srn}. For example, if your SRN is 887766554, you would obtain your data from http://foley.gold.ac.uk/cw20/api/cw1/887766554. If you have difficulties obtaining your exercise data, please email us at: [email protected] 

Introduction

You may have noticed that recently there has been a considerable amount of attention and investment directed towards cryptocurrencies, blockchain and Bitcoin. This coursework assignment is designed to help extend your knowledge
in this area by encouraging self-study and creativity. More specifically, through an exercise it makes you implement your own cryptocurrency, which implicitly makes you understand what a blockchain is, and therefore the mechanism that
underpins all cryptocurrencies including Bitcoin, Litecoin, Ethereum, etc. The nternet has plenty of information on the subject, so you will not find it difficult to research. Your reading should cover the following topics:
 
  • The general idea behind blockchain.
  • Cryptographic hash functions and security of SHA-256.
  • Merkle trees.
  • Proof-of-work algorithms. 
Here are a few starting points for your research:
The coursework is composed of two parts, an exercise and a report. Both parts carry equal marks. In the exercise you should add a few blocks with a few transactions each to a simplified initial blockchain that you have been provided
with, and submit the result in a specific format. In the report you should answer the questions laid out below.
 
To solve the exercise, you may find it necessary to write a program. You are welcome to use any programming language and you are welcome to use any third-party libraries available for SHA-256 and JSON. Libraries are available for most languages, including – and not limited to – Java, C/C++, Scala, Python,JavaScript. Please include key snippets of your code as an annex to your report. You should read the coursework assignment carefully and pay particular attention to the Submission requirements. 

Part A – Exercise

You have been provided with a wallet and a blockchain with a genesis block similar to the following (this is an example for illustration): http://foley.gold.ac. uk/cw20/api/cw1/887766554.
The 
genesis block contains one special transaction that does not have any inputs, and which gives you 100 coins. The genesis block is a special block, being the first one, its reference to the hash of the previous block is “0”. Also, the Merkle root of the genesis block is the same as the hash of the only transaction in the block. The transaction in the genesis block is sent and signed by a special wallet, referred to as the coinbase, which has the following keys: http: //foley.gold.ac.uk/cw20/coinbase.json. 
The exercise consists of adding two blocks to the blockchain:
1. The first block should comprise of two transactions:
• You sending 40 coins to Alice,
• You sending 30 coins to Bob.
2. The second block should comprise of two transactions:
• Alice sending 20 coins to Bob,
• Bob sen.  

Alice’s wallet is: http://foley.gold.ac.uk/cw20/wallet-alice.json.
Bob’s wallet is:
http://foley.gold.ac.uk/cw20/wallet-bob.json.

The transactions have to be valid transactions, the Merkle roots of the blocks have to be calculated, the blocks have to be mined and properly chained up to the genesis block. The difficulty level of the mining is 3.

For the example wallet and inital blockchain that Carl Davis would have received as assignment, from the example above, he would submit the following JSON, which reflects a correct solution: http://foley.gold.ac.uk/cw20/CarlDavis_88776 6554_CO3326cw1.json. 

Clarifications

The fields are self-explanatory and their significance will become evident during the course of your research on blockchains. However, a few clarifications are necessary:
• All keys (public and private keys) as well as signatures and verifications rely on the Elliptic Curve Digital Signature Algorithm (ECDSA). You are not expected to understand the inner workings of this algorithm for this coursework, and it is perfectly acceptable for you to rely on third-party libraries for key related operations, for example Bouncy Castle, which provides libraries for all major programming languages. 
Somewhere in your code you will have to initialise the security provider. If you are using Java and Bouncy Castle, you can do it like this: 
import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
...
public static void main(String[] args) {
...
Security.
addProvider(new BouncyCastleProvider());
...
}
Here is an example in Java to convert the keys you have been given to PublicKey and PrivateKey instances that you can use in your code:
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.apache.commons.codec.binary.Hex;
...
PublicKey 
getPublicKeyFromString(final String publicKeyStr) {
try {
X509EncodedKeySpec spec =
new X509EncodedKeySpec(Hex.decodeHex(publicKeyStr));
KeyFactory factory = KeyFactory.
getInstance("ECDSA""BC");
return factory.generatePublic(spec);
catch (Exception e) {
throw new IllegalStateException(
"Can't transform [" + publicKeyStr + "] to PublicKey", e);
}
}
PrivateKey 
getPrivateKeyFromString(final String privateKeyStr) {
try {
PKCS8EncodedKeySpec spec =
new PKCS8EncodedKeySpec(Hex.decodeHex(privateKeyStr)); 
KeyFactory factory = KeyFactory.getInstance("ECDSA""BC");
return factory.generatePrivate(spec);
catch (Exception e) {
throw new IllegalStateException(
"Can't transform [" + privateKeyStr + "] to PrivateKey", e);
}
}
 

• For hashing the SHA-256 algorithm should be used. The bytes are encoded as UTF_8 and the hashes should be encoded as hexadecimal. 

Here is an example in Java:

import java.security.MessageDigest;
...
String 
applySha256(final String input) {
try {
MessageDigest digest = MessageDigest.
getInstance("SHA-256");
// Applies SHA-256 to our input
byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
// This will contain the hash as hexidecimal
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.
toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.
append(hex);
}
return hexString.toString();
catch (Exception e) {
throw new IllegalStateException(e);
}
}
 
• To sign a transaction, simply concatenate the constituent string fields (i.e. senderrecipient and value in this order) before signing it with the right private key: 
void generateSignature(PrivateKey privateKey) {
String data = sender + recipient + value;
signature = applyECDSASig(privateKey, data);
}
// Applies ECDSA Signature and returns the result (as bytes).
byte[] applyECDSASig(PrivateKey privateKey, String input) {
try {
Signature dsa = Signature.getInstance("ECDSA", "BC");
dsa.initSign(privateKey); 
byte[] strByte = input.getBytes();
dsa.update(strByte);
return dsa.sign();
catch (Exception e) {
throw new IllegalStateException(e);
}

• To calculate the hash of a transaction, similarly concatenate the constituent string fields (i.e. senderrecipientvalue and sequence in this order) before applying SHA-256: 
void calulateHash() {
hash = applySha256(sender + recipient + value + sequence);

• To calculate the hash of a block, concatenate the constituent fields (i.e. previousHashtimeStampnonce and merkleRoot in this order) before applying SHA-256:
void calculateHash(final Block block) {
hash = 
applySha256(previousHash + timeStamp + nonce + merkleRoot);
}
 

Part B – Report

Please answer the questions briefly and in your own words. Use diagrams where possible and explain them. Copy-pasting Wikipedia articles or verbose explanations will not get you very far. Wherever you are asked to provide an example, do so with references to fields and figures in the exercise. 

Question 1

Explain briefly what is meant by Blockchain being referred to as:
"Ledger - Trust + Cryptography".

Question 2

In general terms, how does sending coins in a cryptocurrency work? What is the send-to address? Which fields make sure – and how – that transactions cannot be altered by nodes on the network? 

Question 3

What are the inputs and the outputs of a transaction? Instead of a ledger of balances, what do nodes actually keep track of? What does it take to figure out your own balance?

Question 4

What is double spending?

Question 5

What is the difference between a transaction chain and the block chain?

Question 6

Which field stops the ability of nodes on the network to duplicate transactions?

Question 7

Describe briefly how Merkle Trees help in pinpointing a mismatching transaction between two blocks without comparing each and every transaction.

Question 8

How do all nodes on the network arrive at a consensus with regards to the ordering of transactions?

Question 9

Explain briefly what it would take for Alice to defraud Bob and how Bitcoin prevents this 

Question 10

What would happen if 90 per cent of miners were suddenly shut out of the network for a prolonged period?

Reminder: do not forget to acknowledge all sources. Make sure you acknowledge any code re-use. It is important that your submitted coursework assignment is your own individual work and, for the most part, written in your own words.
You must provide appropriate in-text citation for both paraphrase and quotation, with a detailed reference section at the end of your coursework. Copying, plagiarism and unaccredited and wholesale reproduction of material from books or from any online source is unacceptable, and will be penalised (see our 

You must provide appropriate in-text citation for both paraphrase and quotation, with a detailed reference section at the end of your coursework. Copying, plagiarism and unaccredited and wholesale reproduction of material from books or from any online source is unacceptable, and will be penalised (see our guide on how to avoid plagiarism on the VLE). 

Submission requirements

You should upload two single files only. These must not be placed in a folder, zipped, etc.

The report should be submitted as a PDF document using the below file-naming conventions: YourName_SRN_COxxxcw#.pdf, for example CarlDavis_887766554_CO3326cw1.pdfYourName is your full name as it appears on your student record (check your student portal), SRN is your Student Reference Number, for example 887766554COXXXX is the course number, for example CO3326, and cw# is either cw1 (coursework 1) or cw2 (coursework 2).

The exercise should be submitted as a JSON file with a strict format and naming scheme. The exercise will be automatically checked by an algorithm, so pay particular attention to its format. The name of the file should be YourName_{srn}_CO3326cw1.json; for example, Carl Davis with SRN 887766554 would submit CarlDavis_887766554_CO3326cw1.json.

NOTE: As the JSON is evaluated by an algorithm, every quote, comma, colon, curly brace upper/lower case is crucial. Please pay attention to these. It would be a shame to lose a potential 50% of the total marks for this coursework
assignment because of a misplaced comma or a missing quote. There are online tools you can use for JSON formatting and validation, for example 

assignment because of a misplaced comma or a missing quote. There are online tools you can use for JSON formatting and validation, for example https://jsonformatter.curiousconcept.com/, so double-check that your JSON is
syntactically correct.