From 763c968a727f0acdd993e4726020c3e2509313c8 Mon Sep 17 00:00:00 2001 From: Steven Tracey Date: Sun, 21 Nov 2021 20:35:10 -0500 Subject: [PATCH] Blockchain! --- .gitignore | 154 +++++++++++++++ .idea/.gitignore | 8 + .idea/compiler.xml | 6 + .idea/jarRepositories.xml | 20 ++ .idea/misc.xml | 10 + .idea/runConfigurations.xml | 10 + .idea/vcs.xml | 6 + README.md | 3 + build.gradle | 18 ++ gradle/wrapper/gradle-wrapper.properties | 5 + gradlew | 185 ++++++++++++++++++ gradlew.bat | 89 +++++++++ settings.gradle | 2 + src/main/java/tech/nevets/nevcoin/Block.java | 61 ++++++ .../java/tech/nevets/nevcoin/NevCoin.java | 143 ++++++++++++++ src/main/java/tech/nevets/nevcoin/Wallet.java | 75 +++++++ .../nevcoin/transactions/Transaction.java | 95 +++++++++ .../transactions/TransactionInput.java | 11 ++ .../transactions/TransactionOutput.java | 22 +++ .../tech/nevets/nevcoin/util/StringUtil.java | 92 +++++++++ 20 files changed, 1015 insertions(+) create mode 100644 .gitignore create mode 100644 .idea/.gitignore create mode 100644 .idea/compiler.xml create mode 100644 .idea/jarRepositories.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/runConfigurations.xml create mode 100644 .idea/vcs.xml create mode 100644 README.md create mode 100644 build.gradle create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle create mode 100644 src/main/java/tech/nevets/nevcoin/Block.java create mode 100644 src/main/java/tech/nevets/nevcoin/NevCoin.java create mode 100644 src/main/java/tech/nevets/nevcoin/Wallet.java create mode 100644 src/main/java/tech/nevets/nevcoin/transactions/Transaction.java create mode 100644 src/main/java/tech/nevets/nevcoin/transactions/TransactionInput.java create mode 100644 src/main/java/tech/nevets/nevcoin/transactions/TransactionOutput.java create mode 100644 src/main/java/tech/nevets/nevcoin/util/StringUtil.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..620dd00 --- /dev/null +++ b/.gitignore @@ -0,0 +1,154 @@ +# ---> Gradle +.gradle +build/ +!src/**/build/ +!**/src/main/**/build/ +!**/src/test/**/build/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ +bin/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Cache of project +.gradletasknamecache + +# ---> Java +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# ---> JetBrains +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +# ---> Windows +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..fb7f4a8 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..fdc392f --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..2fccad5 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100644 index 0000000..797acea --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..64187ef --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# NevCoin + +Personal Blockchain! \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..74fba9f --- /dev/null +++ b/build.gradle @@ -0,0 +1,18 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '2.6.0' + id 'io.spring.dependency-management' version '1.0.11.RELEASE' +} + +group 'tech.nevets' +version '1.0' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'com.google.code.gson:gson:2.8.9' + implementation group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.52' + implementation 'org.springframework.boot:spring-boot-starter' +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..69a9715 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..744e882 --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MSYS* | MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..64a8c83 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'NevCoin' + diff --git a/src/main/java/tech/nevets/nevcoin/Block.java b/src/main/java/tech/nevets/nevcoin/Block.java new file mode 100644 index 0000000..53ae167 --- /dev/null +++ b/src/main/java/tech/nevets/nevcoin/Block.java @@ -0,0 +1,61 @@ +package tech.nevets.nevcoin; + +import tech.nevets.nevcoin.transactions.Transaction; +import tech.nevets.nevcoin.util.StringUtil; + +import java.util.ArrayList; +import java.util.Date; + +public class Block { + + public String hash; + public String previousHash; + public String merkleRoot; + public ArrayList transactions = new ArrayList(); + //private String data; + private long timeStamp; + private int nonce; + + public Block(String previousHash) { + //this.data = data; + this.previousHash = previousHash; + this.timeStamp = new Date().getTime(); + this.hash = calculateHash(); + } + + public String calculateHash() { + String calculatedHash = StringUtil.applySha256( + previousHash + + Long.toString(timeStamp) + + Integer.toString(nonce) + + merkleRoot + //+ data + ); + return calculatedHash; + } + + public void mineBlock(int difficulty) { + merkleRoot = StringUtil.getMerkleRoot(transactions); + String target = StringUtil.getDifficultyString(difficulty); + + while (!hash.substring(0, difficulty).equals(target)) { + nonce ++; + hash = calculateHash(); + } + System.out.println("Block mined: " + hash); + } + + public boolean addTransaction(Transaction transaction) { + if (transaction == null) return false; + if (!"0".equals(previousHash)) { + if (transaction.processTransaction() != true) { + System.out.println("Transaction failed to process. Discarded."); + return false; + } + } + + transactions.add(transaction); + System.out.println("Transaction Successfully added to Block"); + return true; + } +} diff --git a/src/main/java/tech/nevets/nevcoin/NevCoin.java b/src/main/java/tech/nevets/nevcoin/NevCoin.java new file mode 100644 index 0000000..7452ea1 --- /dev/null +++ b/src/main/java/tech/nevets/nevcoin/NevCoin.java @@ -0,0 +1,143 @@ +package tech.nevets.nevcoin; + +import tech.nevets.nevcoin.transactions.Transaction; +import tech.nevets.nevcoin.transactions.TransactionInput; +import tech.nevets.nevcoin.transactions.TransactionOutput; + +import java.security.Security; +import java.util.ArrayList; +import java.util.HashMap; + +public class NevCoin { + + public static ArrayList blockChain = new ArrayList(); + public static HashMap UTXOs = new HashMap(); + + public static int difficulty = 10; + public static float minimumTransaction = 0.1f; + public static Wallet walletA; + public static Wallet walletB; + public static Transaction genesisTransaction; + + public static void main(String[] args) { + + Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); + + walletA = new Wallet(); + walletB = new Wallet(); + Wallet coinbase = new Wallet(); + + genesisTransaction = new Transaction(coinbase.publicKey, walletA.publicKey, 100f, null); + genesisTransaction.generateSignature(coinbase.privateKey); + genesisTransaction.transactionId = "0"; + genesisTransaction.outputs.add(new TransactionOutput(genesisTransaction.recipient, genesisTransaction.value, genesisTransaction.transactionId)); + UTXOs.put(genesisTransaction.outputs.get(0).id, genesisTransaction.outputs.get(0)); + + System.out.println("Creating and Mining Genesis block... "); + Block genesis = new Block("0"); + genesis.addTransaction(genesisTransaction); + addBlock(genesis); + + Block block1 = new Block(genesis.hash); + System.out.println("\nWalletA's balance is: " + walletA.getBalance()); + System.out.println("\nWalletA is Attempting to send funds (40) to WalletB..."); + block1.addTransaction(walletA.sendFunds(walletB.publicKey, 40f)); + addBlock(block1); + System.out.println("\nWalletA's balance is: " + walletA.getBalance()); + System.out.println("WalletB's balance is: " + walletB.getBalance()); + + Block block2 = new Block(block1.hash); + System.out.println("\nWalletA Attempting to send more funds (1000) than it has..."); + block2.addTransaction(walletA.sendFunds(walletB.publicKey, 1000f)); + addBlock(block2); + System.out.println("\nWalletA's balance is: " + walletA.getBalance()); + System.out.println("WalletB's balance is: " + walletB.getBalance()); + + Block block3 = new Block(block2.hash); + System.out.println("\nWalletB is Attempting to send funds (20) to WalletA..."); + block3.addTransaction(walletB.sendFunds( walletA.publicKey, 20)); + System.out.println("\nWalletA's balance is: " + walletA.getBalance()); + System.out.println("WalletB's balance is: " + walletB.getBalance()); + + isChainValid(); + + } + + public static Boolean isChainValid() { + Block currentBlock; + Block previousBlock; + String hashTarget = new String(new char[difficulty]).replace('\0', '0'); + HashMap tempUTXOs = new HashMap(); + tempUTXOs.put(genesisTransaction.outputs.get(0).id, genesisTransaction.outputs.get(0)); + + for (int i = 1; i < blockChain.size(); i++) { + + currentBlock = blockChain.get(i); + previousBlock = blockChain.get(i - 1); + + if (!currentBlock.hash.equals(currentBlock.calculateHash())) { + System.out.println("Current Hashes not equal"); + return false; + } + + if (!previousBlock.hash.equals(currentBlock.previousHash)) { + System.out.println("Previous Hashes not equal"); + return false; + } + + if (!currentBlock.hash.substring(0, difficulty).equals(hashTarget)) { + System.out.println("This block hasn't been mined"); + return false; + } + + TransactionOutput tempOutput; + for (int t = 0; t < currentBlock.transactions.size(); t++) { + Transaction currentTransaction = currentBlock.transactions.get(t); + + if (!currentTransaction.verifySignature()) { + System.out.println("#Signature on Transaction(" + t + ") is Invalid"); + return false; + } + if (currentTransaction.getInputsValue() != currentTransaction.getOutputsValue()) { + System.out.println("#Inputs are note equal to outputs on Transaction(" + t + ")"); + return false; + } + + for (TransactionInput input: currentTransaction.inputs) { + tempOutput = tempUTXOs.get(input.transactionOutputId); + + if (tempOutput == null) { + System.out.println("#Referenced input on Transaction(" + t + ") is Missing"); + return false; + } + + if (input.UTXO.value != tempOutput.value) { + System.out.println("#Referenced input Transaction(" + t + ") value is Invalid"); + return false; + } + + tempUTXOs.remove(input.transactionOutputId); + } + + for (TransactionOutput output: currentTransaction.outputs) { + tempUTXOs.put(output.id, output); + } + + if (currentTransaction.outputs.get(0).recipient != currentTransaction.recipient) { + System.out.println("#Transaction(" + t + ") output recipient is not who it should be"); + return false; + } + if (currentTransaction.outputs.get(1).recipient != currentTransaction.sender) { + System.out.println("#Transaction(" + t + ") output 'change' is not sender."); + return false; + } + } + } + return true; + } + + public static void addBlock(Block newBlock) { + newBlock.mineBlock(difficulty); + blockChain.add(newBlock); + } +} \ No newline at end of file diff --git a/src/main/java/tech/nevets/nevcoin/Wallet.java b/src/main/java/tech/nevets/nevcoin/Wallet.java new file mode 100644 index 0000000..929973e --- /dev/null +++ b/src/main/java/tech/nevets/nevcoin/Wallet.java @@ -0,0 +1,75 @@ +package tech.nevets.nevcoin; + +import tech.nevets.nevcoin.transactions.Transaction; +import tech.nevets.nevcoin.transactions.TransactionInput; +import tech.nevets.nevcoin.transactions.TransactionOutput; + +import java.security.*; +import java.security.spec.ECGenParameterSpec; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class Wallet { + public PrivateKey privateKey; + public PublicKey publicKey; + + public HashMap UTXOs = new HashMap(); + + public Wallet() { + generateKeyPair(); + } + + public void generateKeyPair() { + try { + KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA", "BC"); + SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); + ECGenParameterSpec ecSpec = new ECGenParameterSpec("prime192v1"); + + keyGen.initialize(ecSpec, random); + KeyPair keyPair = keyGen.generateKeyPair(); + + privateKey = keyPair.getPrivate(); + publicKey = keyPair.getPublic(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public float getBalance() { + float total = 0; + for (Map.Entry item: NevCoin.UTXOs.entrySet()) { + TransactionOutput UTXO = item.getValue(); + if (UTXO.isMine(publicKey)) { + UTXOs.put(UTXO.id, UTXO); + total += UTXO.value ; + } + } + return total; + } + + public Transaction sendFunds(PublicKey _recipient, float value ) { + if(getBalance() < value) { + System.out.println("#Not Enough funds to send transaction. Transaction Discarded."); + return null; + } + ArrayList inputs = new ArrayList(); + + float total = 0; + for (Map.Entry item: UTXOs.entrySet()) { + TransactionOutput UTXO = item.getValue(); + total += UTXO.value; + inputs.add(new TransactionInput(UTXO.id)); + if (total > value) break; + } + + Transaction newTransaction = new Transaction(publicKey, _recipient, value, inputs); + newTransaction.generateSignature(privateKey); + + for (TransactionInput input: inputs) { + UTXOs.remove(input.transactionOutputId); + } + + return newTransaction; + } +} \ No newline at end of file diff --git a/src/main/java/tech/nevets/nevcoin/transactions/Transaction.java b/src/main/java/tech/nevets/nevcoin/transactions/Transaction.java new file mode 100644 index 0000000..45eb326 --- /dev/null +++ b/src/main/java/tech/nevets/nevcoin/transactions/Transaction.java @@ -0,0 +1,95 @@ +package tech.nevets.nevcoin.transactions; + +import tech.nevets.nevcoin.NevCoin; +import tech.nevets.nevcoin.util.StringUtil; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.util.ArrayList; + +public class Transaction { + public String transactionId; + public PublicKey sender; + public PublicKey recipient; + public float value; + public byte[] signature; + + public ArrayList inputs = new ArrayList(); + public ArrayList outputs = new ArrayList(); + + private static int sequence = 0; + + public Transaction(PublicKey from, PublicKey to, float value, ArrayList inputs) { + this.sender = from; + this.recipient = to; + this.value = value; + this.inputs = inputs; + } + + public boolean processTransaction() { + if (verifySignature() == false) { + System.out.println("#Transaction Signature failed to verify"); + return false; + } + + for (TransactionInput i : inputs) { + i.UTXO = NevCoin.UTXOs.get(i.transactionOutputId); + } + + if (getInputsValue() < NevCoin.minimumTransaction) { + System.out.println("#Transaction Inputs to small: " + getInputsValue()); + return false; + } + + float leftOver = getInputsValue() - value; + transactionId = calculateHash(); + outputs.add(new TransactionOutput( this.recipient, value, transactionId)); + outputs.add(new TransactionOutput( this.sender, leftOver, transactionId)); + + for (TransactionOutput o : outputs) { + NevCoin.UTXOs.put(o.id, o); + } + + for (TransactionInput i : inputs) { + if (i.UTXO == null) continue; //if Transaction can't be found skip it + NevCoin.UTXOs.remove(i.UTXO.id); + } + + return true; + } + + public float getInputsValue() { + float total = 0; + for (TransactionInput i : inputs) { + if (i.UTXO == null) continue; //if Transaction can't be found skip it + total += i.UTXO.value; + } + return total; + } + + public void generateSignature(PrivateKey privateKey) { + String data = StringUtil.getStringFromKey(sender) + StringUtil.getStringFromKey(recipient) + Float.toString(value) ; + signature = StringUtil.applyECDSASig(privateKey, data); + } + + public boolean verifySignature() { + String data = StringUtil.getStringFromKey(sender) + StringUtil.getStringFromKey(recipient) + Float.toString(value) ; + return StringUtil.verifyECDSASig(sender, data, signature); + } + + public float getOutputsValue() { + float total = 0; + for(TransactionOutput o : outputs) { + total += o.value; + } + return total; + } + + private String calculateHash() { + sequence++; + return StringUtil.applySha256( + StringUtil.getStringFromKey(sender) + + StringUtil.getStringFromKey(recipient) + + Float.toString(value) + sequence + ); + } +} diff --git a/src/main/java/tech/nevets/nevcoin/transactions/TransactionInput.java b/src/main/java/tech/nevets/nevcoin/transactions/TransactionInput.java new file mode 100644 index 0000000..031953e --- /dev/null +++ b/src/main/java/tech/nevets/nevcoin/transactions/TransactionInput.java @@ -0,0 +1,11 @@ +package tech.nevets.nevcoin.transactions; + +public class TransactionInput { + + public String transactionOutputId; + public TransactionOutput UTXO; + + public TransactionInput(String transactionOutputId) { + this.transactionOutputId = transactionOutputId; + } +} diff --git a/src/main/java/tech/nevets/nevcoin/transactions/TransactionOutput.java b/src/main/java/tech/nevets/nevcoin/transactions/TransactionOutput.java new file mode 100644 index 0000000..827b5b2 --- /dev/null +++ b/src/main/java/tech/nevets/nevcoin/transactions/TransactionOutput.java @@ -0,0 +1,22 @@ +package tech.nevets.nevcoin.transactions; + +import tech.nevets.nevcoin.util.StringUtil; +import java.security.PublicKey; + +public class TransactionOutput { + public String id; + public PublicKey recipient; + public float value; + public String parentTransactionId; + + public TransactionOutput(PublicKey recipient, float value, String parentTransactionId) { + this.recipient = recipient; + this.value = value; + this.parentTransactionId = parentTransactionId; + this.id = StringUtil.applySha256(StringUtil.getStringFromKey(recipient) + Float.toString(value)+parentTransactionId); + } + + public boolean isMine(PublicKey publicKey) { + return (publicKey == recipient); + } +} diff --git a/src/main/java/tech/nevets/nevcoin/util/StringUtil.java b/src/main/java/tech/nevets/nevcoin/util/StringUtil.java new file mode 100644 index 0000000..004f088 --- /dev/null +++ b/src/main/java/tech/nevets/nevcoin/util/StringUtil.java @@ -0,0 +1,92 @@ +package tech.nevets.nevcoin.util; + +import com.google.gson.GsonBuilder; +import tech.nevets.nevcoin.transactions.Transaction; + +import java.security.*; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; + +public class StringUtil { + + public static String applySha256(String input) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] hash = digest.digest(input.getBytes("UTF-8")); + StringBuffer hexString = new StringBuffer(); + + for (int i = 0; i < hash.length; i++) { + String hex = Integer.toHexString(0xff & hash[i]); + + if (hex.length() == 1) hexString.append('0'); + hexString.append(hex); + } + return hexString.toString(); + + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static byte[] applyECDSASig(PrivateKey privateKey, String input) { + Signature dsa; + byte[] output = new byte[0]; + try { + dsa = Signature.getInstance("ECDSA", "BC"); + dsa.initSign(privateKey); + byte[] strByte = input.getBytes(); + dsa.update(strByte); + byte[] realSig = dsa.sign(); + output = realSig; + } catch (Exception e) { + throw new RuntimeException(e); + } + return output; + } + + public static boolean verifyECDSASig(PublicKey publicKey, String data, byte[] signature) { + try { + Signature ecdsaVerify = Signature.getInstance("ECDSA", "BC"); + ecdsaVerify.initVerify(publicKey); + ecdsaVerify.update(data.getBytes()); + return ecdsaVerify.verify(signature); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static String getJson(Object o) { + return new GsonBuilder().setPrettyPrinting().create().toJson(o); + } + + public static String getDifficultyString(int difficulty) { + return new String(new char[difficulty]).replace('\0', '0'); + } + + public static String getStringFromKey(Key key) { + return Base64.getEncoder().encodeToString(key.getEncoded()); + } + + public static String getMerkleRoot(ArrayList transactions) { + int count = transactions.size(); + + List previousTreeLayer = new ArrayList(); + for (Transaction transaction : transactions) { + previousTreeLayer.add(transaction.transactionId); + } + List treeLayer = previousTreeLayer; + + while (count > 1) { + treeLayer = new ArrayList(); + for(int i=1; i < previousTreeLayer.size(); i += 2) { + treeLayer.add(applySha256(previousTreeLayer.get(i - 1) + previousTreeLayer.get(i))); + } + count = treeLayer.size(); + previousTreeLayer = treeLayer; + } + + String merkleRoot = (treeLayer.size() == 1) ? treeLayer.get(0) : ""; + return merkleRoot; + } +}