Giter VIP home page Giter VIP logo

savjeecoin's Introduction

Project logo

SavjeeCoin

.github/workflows/ci.yml Coverage Status GitHub Issues GitHub Pull Requests License


⚠️ For education purposes only. This is by no means a complete implementation and it is by no means secure!

Features

  • Simple proof-of-work algorithm
  • Verify blockchain (to prevent tampering)
  • Generate wallet (private/public key)
  • Sign transactions

🏁 Getting Started

Install library

npm install --save savjeecoin

Generate a keypair

To make transactions on this blockchain you need a keypair. The public key becomes your wallet address and the private key is used to sign transactions.

const EC = require('elliptic').ec;
const ec = new EC('secp256k1');

const myKey = ec.genKeyPair();

The myKey object now contains your public & private key:

console.log('Public key:', myKey.getPublic('hex'));
console.log('Private key:', myKey.getPrivate('hex'));

Create a blockchain instance

Now you can create a new instance of a Blockchain:

const {Blockchain, Transaction} = require('savjeecoin');

const myChain = new Blockchain();

Adding transactions

// Transfer 100 coins from my wallet to "toAddress"
const tx = new Transaction(myKey.getPublic('hex'), 'toAddress', 100);
tx.sign(myKey);

myChain.addTransaction(tx);

To finalize this transaction, we have to mine a new block. We give this method our wallet address because we will receive a mining reward:

myChain.minePendingTransactions(myKey.getPublic('hex'));

πŸ“½ Video tutorial

This source code comes from my video series on YouTube. You can check them here:

Video 1: Simple implementation Video 2: Adding Proof-of-work
Video 3: Mining rewards & transactions Video 4: Signing transactions
Video 5: Building a front-end in Angular

savjeecoin's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

savjeecoin's Issues

Account balance can't be negative

image

Image attached shows the transactions that lead to negative balance on account.
The transaction should not be executed if the user doesn't have enough money.
I suppose the Wallet should be added.

Wrong function isChainValid()

Hey Savjee, I reworked this function because the first block of the chain is not checked.
With this function change, you can do this by checking the first block.

isChainValid() {
    for(let i=0; i<this.chain.length; i++){

        if(this.chain[i].hash !== this.chain[i].calculateHash())
            return false;

        if(i > 0 && this.chain[i].previousHash !== this.chain[i-1].hash)
            return false;
    }

    return true;
}

With kind regards
CrafterGamer

Next steps?

Hi @Savjee, I've been following your series of posts and I really enjoyed that.

I do not like the idea of ​​"reinventing the wheel", but if you intend to create some decentralized solution that uses a blockchain template, you can do thousands of searches (from various sources) (Googling) that only topics related to "cryptocurrency" flood the content.

Virtually most solutions, services and tools have open sources that can be studied and documentation plentiful but, you end up stuck or one or the other ... it is extremely scarce to find blockchain materials that are not solely and exclusively related to "cryptocurrency ". I really do not believe that I should "mold" my problems in order to use the available libraries simply because of the lack of a minimally qualified material.

I think at this point that your series of posts has been very didactic and helps better understand the operation of a blockchain than many low-level matters that it has there.

I'm studying the use of a front-end blockchain using WebRTC (DataChannel), and I'm leveraging their stuff to better understand how it works. In the last post it seems to me that you have gone in the direction of an active chain (cryptocurrency).

I wonder if you have thoughts about continuing the series of posts and plans to talk about wallets or contracts?

how to connect with local host or database?

Dear Sir,

Thank you for this inspiring and cool example, but i've found difficulties to connect to database to my local host?
how to do it?
and pardon me..when i do commit git i commit here...how to commit to my own git...sorry in advance...

Genesis block doesn't follow the difficulty

Hey, I just wanted to test the blockchain but then I realized the genesis block's hash doesn't follow the difficulty. I tried solving it by adding this code to the createGenesisBlock() function in line 139 of blockchain.js file:
const genblock = new Block(Date.parse('2017-01-01'), [], '0');
genblock.mineBlock(this.difficulty);
return genblock;

but it didn't work. Can someone please help.

TypeError: Block is not a constructor

I get this error any fix?

TypeError: Block is not a constructor
at Blockchain.createGenesisBlock (C:\Users\PC\Desktop\BLOCKCHAIN\blockchain.js:10:16)
at new Blockchain (C:\Users\PC\Desktop\BLOCKCHAIN\blockchain.js:5:28)
at Object. (C:\Users\PC\Desktop\BLOCKCHAIN\blockchain.js:27:19)
at Module._compile (node:internal/modules/cjs/loader:1108:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47
PS C:\Users\PC\Desktop\BLOCKCHAIN>

Fix for double spending during mining

addTransaction() method checks for double spending by doing getBalanceOfAddress() check link, but a user can add any number of transactions even if s/he doesnt have the balance. Shouldn't we add the same check for each transaction in the minePendingTransactions() link, so that we can remove the problem of double spending. If this sounds good, I will raise the pull request.

Prettier and strict mode

I am a bit of a newb, so this may be a dumb question, but should the JS files be re-formatted using VSCode's "Prettier" extension for easier readability, and should they also have "strict" mode implemented to help catch and prevent more errors?

Just wonderingπŸ™‚

Subject of decentralization, worker nodes and wallets

Hi!

First, thank you so much for this great work, truly a great way to understand blockchain from implementation standpoint.
Not really an issue, but this is the fastest way I could think of to contact you regarding this project. Are there any plans to continue with this, specifically to explain and implement support for decentralization and multiple worker (mining) nodes. This would answer many questions such as how real nodes actually acquire transactions to embed into the block prior to mining, how synchronization works between various nodes etc. It would also split the project into clearly visible separate components of the entire system (to see which logic is actually implemented on the wallet side, and which on worker side). And the burning question for me is, if I'm a new node, how and from who do I acquire my blockchain copy and how do I broadcast my existence to everyone else?

I know, lots of ideas and lots of text, but I hope this could be a future of the project, at least in some far future time :) maybe I even jump in with some pull requests then.

PreviousHash is always ''

I am rewriting the code into c#, so I can see for myself how it works ... and it seems to me that previousHash will always be '' (empty) in your example.

I have not run the code, so i might be reading it wrong.

Line 56 of main.js has this :
savjeeCoin.addBlock(new Block(1, "20/07/2017", { amount: 4 }));
The previousHash should be passed in from my understanding.

BTW. Brilliant video and explenation!

Hard to know the valid src.

@Savjee
Thanks a lot for this great work , it surely a great one I have been watching your YouTube video series on this repo, but the SRC structure is a bit different.
And on the newest update.

Missing previous block hash?

Hello Savjee,

Correct me if I'm wrong, but in the third version of this code, shouldn't we add the latest block's hash when creating a new block in minePendingTransactions. Doesn't this ensure the integrity of our chain, were someone to try and alter a block?

for example:

  minePendingTransactions(miningRewardAddress) {
	let block = new Block(Date.now(), this.pendingTransactions, this.getLatestBlock().hash);
	block.mineBlock(this.difficulty);

	this.chain.push(block);
		
	this.pendingTransactions = [
		new Transaction(null, miningRewardAddress, this.miningReward)
	];
  }

also one small matter of cleanup, we no longer need to include this.index in the calculateHash function.

Thanks for the tutorials! They have definitely helped me to better understand what a blockchain is.

Reward transaction does not get signed

Hello, great job on this project!

EDIT: Nevermind. A transaction is valid when a null sender is set.

Please, I would like to draw your attention to the Blockchain.minePendingTransactions() method (here):

minePendingTransactions(miningRewardAddress) {
    const rewardTx = new Transaction(null, miningRewardAddress, this.miningReward);
    this.pendingTransactions.push(rewardTx);

    const block = new Block(Date.now(), this.pendingTransactions, this.getLatestBlock().hash);
    block.mineBlock(this.difficulty);

    debug('Block successfully mined!');
    this.chain.push(block);
    this.pendingTransactions = []; 
}

The rewardTx is inserted into the pending transactions array without getting signed by the sender which causes the transaction to be invalid (when verified using the Transaction.isValid() method.)

Reading data from a block

Hi @Savjee, great tutorial! I learned a lot about how blockchain works as you speak my language (javascript) ;)

Question, what would it take in your example to decrypt/read the data from a specific block?

Thanks!

reward transaction not signed?

Hello, the transaction rewardTx is not signed, so Transaction.signature is not set for it; this is in minePendingTransactions in blockchain.js.
Is that deliberate? Incidentally in class Transaction there is no constructor signature.

TypeError: Transaction is not a constructor

I keep getting the error
TypeError: Transaction is not a constructor
every time I try and run the code. How do I fix this? I know I need to add a constructor, but I am new to this so how do I do that?

Running node getting SyntaxError: Unexpected identifier

When I run node main.js, at 8:30 in the video, at the first console log, I get the below Syntax error.

I created a plugin in my wordpress installation called my-blockchain, put your savjeecoin code in my-blockchain/js/main.js and called the main.js file in my plugin php file: require 'js/main.js';

Help!

Marks-MacBook-Pro:js marklovett$ npm -v
5.6.0
Marks-MacBook-Pro:js marklovett$ node -v
v8.10.0
Marks-MacBook-Pro:js marklovett$ npm outdated
Package Current Wanted Latest Location
crypto-js 3.1.8 3.1.8 3.1.9-1
Marks-MacBook-Pro:js marklovett$ node main.js
/Users/marklovett/test-project/wordpress/wp-content/plugins/my-blockchain/js/main.js:65
let savjeeCoin = new Blockchain();
^^^^^^^^^^

SyntaxError: Unexpected identifier
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3

Error: Not enough balance

Error: Not enough balance
    at Blockchain.addTransaction (/Users/mwill/Documents/GitHub/SavjeeCoin/src/blockchain.js:196:13)
    at Object.<anonymous> (/Users/mwill/Documents/GitHub/SavjeeCoin/src/main.js:17:12)
    at Module._compile (internal/modules/cjs/loader.js:955:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
    at internal/main/run_main_module.js:17:11
mwill@Masons-Air SavjeeCoin % 

Not enough balance

After downloading the repository and running it I get the following error:

throw new Error('Not enough balance');

which comes from the following method:

 // Making sure that the amount sent is not greater than existing balance
 if (this.getBalanceOfAddress(transaction.fromAddress) < transaction.amount) {
    throw new Error('Not enough balance');
 }

The only way I was able to make the code work is by removing such method. Is there any solution to make it function correctly please?

Doubt: What is transaction in the block.

First of all, I would really like to thanks to make me understand the concept of Blockchain...

Now doubt :-
Will the transaction in the block be a list of transactions or a block will have a single transaction.. From your code it seems to be the list...

Thanks
SP

Is chain valid? false

After I tried to see if my block was valid but no matter what I did, it still said that it was not valid. I put my code below.
Blockchain.js:
Screen Shot 2022-01-18 at 2 46 10 PM
Screen Shot 2022-01-18 at 2 46 21 PM
Screen Shot 2022-01-18 at 2 46 30 PM
Screen Shot 2022-01-18 at 2 46 41 PM
Screen Shot 2022-01-18 at 2 46 48 PM
Main.js:
Screen Shot 2022-01-18 at 2 50 20 PM
Keygenerator.js:
Screen Shot 2022-01-18 at 2 50 31 PM
Hopefully, someone can help me.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.