GithubHelp home page GithubHelp logo

15dkatz / cryptochain Goto Github PK

View Code? Open in Web Editor NEW
255.0 24.0 221.0 1.75 MB

Build a blockchain-based cryptocurrency on the full stack course

Home Page: https://www.udemy.com/build-blockchain-full-stack

JavaScript 98.26% CSS 0.92% HTML 0.82%

cryptochain's Introduction

Build a Blockchain and Cryptocurrency | Full-Stack Edition

Course Logo

This is the official code for the Build a Blockchain and Cryptocurrency | Full-Stack Edition course on Udemy by David Katz. Also, be sure to check out the commit-by-commit breakdown of the course for an easier time investigating issues with your project.

References:

Description

The blockchain is a revolutionary technology that allows for the secure, distributed, decentralized storage of information. Over the past few years, the blockchain has taken the engineering landscape by storm. Many people in the industry predict that the blockchain will disrupt the ways we interact with technology on the same way the Internet did in the early 2000s.

This course is a remastered version of the original Build a Blockchain and Cryptocurrency from Scratch course released in early 2018: https://www.udemy.com/build-blockchain.

This takes that course's best content, and adds a ton of additional material: Some of the main course highlights:

  • Code a full-on backend with test-driven development.
  • Write a full test suite for the backend.
  • Build a Blockchain in the object-oriented programming style.
  • Create a full frontend React.js web application.
  • Deploy the application to production (with multiple servers).
  • Create an API around the Blockchain.
  • Create a real-time connected peer-to-peer server with a pub/sub implementation.
  • Implement a proof-of-work algorithm.
  • Sign Transactions with cryptography and digital signature.
  • Create a Transaction Pool for a real-time list of incoming data.
  • Include transactions in core blocks of the chain.

cryptochain's People

Contributors

15dkatz avatar

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

cryptochain's Issues

Duplicate code

This code is duplicate on L28 - L40.

broadcastChain() {
this.publish({
channel: CHANNELS.BLOCKCHAIN,
message: JSON.stringify(this.blockchain.chain)
});
}
broadcastTransaction(transaction) {
this.publish({
channel: CHANNELS.TRANSACTION,
message: JSON.stringify(transaction)
});
}

transaction.input.address error

I'm recieving the following error upon completing my backend and using postman:
`D:\Github\4th-Year-Project-Blockchain-From-Scratch\cryptochain\blockchain\index.js:54
if(transaction.input.address === REWARD_INPUT.address){
^

TypeError: Cannot read properties of undefined (reading 'address')
at Blockchain.validTransactionData (D:\Github\4th-Year-Project-Blockchain-From-Scratch\cryptochain\blockchain\index.js:54:38)
at Blockchain.replaceChain (D:\Github\4th-Year-Project-Blockchain-From-Scratch\cryptochain\blockchain\index.js:35:43)
at PubSub.handleMessage (D:\Github\4th-Year-Project-Blockchain-From-Scratch\cryptochain\app\pubsub.js:40:33)
at Object.message (D:\Github\4th-Year-Project-Blockchain-From-Scratch\cryptochain\app\pubsub.js:70:22)
at D:\Github\4th-Year-Project-Blockchain-From-Scratch\cryptochain\node_modules\pubnub\lib\core\components\listener_manager.js:65:40
at Array.forEach ()
at _class.announceMessage (D:\Github\4th-Year-Project-Blockchain-From-Scratch\cryptochain\node_modules\pubnub\lib\core\components\listener_manager.js:64:23)
at D:\Github\4th-Year-Project-Blockchain-From-Scratch\cryptochain\node_modules\pubnub\lib\core\components\subscription_manager.js:571:35
at Array.forEach ()
at _class._processSubscribeResponse (D:\Github\4th-Year-Project-Blockchain-From-Scratch\cryptochain\node_modules\pubnub\lib\core\components\subscription_manager.js:493:16)
[nodemon] app crashed - waiting for file changes before starting...`

Any ideas as to whats going on? I've literally copied and pasted the repo code to try fix the issue with no success

Orphan blocks and stale blocks

Hi,
I subscribed through your course. I was wondering what happens when a transaction is stored in a stale block. Your code is assuming if once blockchain is broadcasted, it will automatically be part of the longest blockchain. What happens when that blockchain is not accepted and the block becomes a stale block ? The transactions will be lost
Thanks

Frontend Development Workflow

Hi,
I'm following your Udemy course and got stuck at the "Frontend Development Workflow" video...
When I added to my package.json the lines:

image

it is not responding and the local host 3000 is still not working the dev-client server takes over the comment line an still waits
Parcel 1 updated to Parcel 2 maybe this is the problem?

Please help me :)

Minus amount , is a huge miss

Hi, thanks you for the Course, but i mention the it's possible to send minus or 0 value on amount and i think it's will be very danger.
specially for people will really run it as a production.

you can send minus amount on create Transaction eg
image
it will rise sender balance :) for sure -- = +
fix need 2 tests + 2 fix on classes
wallet / index.test.js

			it("throws an error on mins", () => {
				expect(() => {
					wallet.createTransaction({
						recipient: "arabto2-recipient",
						amount: -100,
					});
				}).toThrow("incorrect amount value");
			});

wallet/ index.js

		if (amount <= 0) {
			throw new Error("incorrect amount value");
		} 

------ also on update transaction -----
wallet/transaction.test.js

			it("throws an error on mins", () => {
				expect(() => {
					transaction.update({
						senderWallet,
						recipient: "arabto2-recipient",
						amount: -100,
					});
				}).toThrow("incorrect amount value");
			});

wallet/transaction.js

		if (amount <= 0) {
			throw new Error("incorrect amount value");
		}

also i think it balance shall not accept minus value , the amount also accept alphabet so i even suggest to have method on util to validate the number

$node pubsub.js issue. Lecture 37

Lecture 37 when i run node pubsub.js i get the following error in the console. I believe I installed redis correctly. I get "Configuration loaded" after running redis-server --daemonize yes. I will also include my code from the pubsub class. Thanks for any help.

josh@Josh:~$ node pubsub.js

internal/modules/cjs/loader.js:638
throw err;
^

Error: Cannot find module '/home/josh/pubsub.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

const redis = require('redis');

const CHANNELS = {
    TEST: 'TEST'
};


class PubSub {
    constructor(){
        this.publisher = redis.createClient();
        this.subscriber = redis.createClient();

        this.subscriber.subscribe(CHANNELS.TEST);

        this.subscriber.on(
            'message', 
            (channel, message) => this.handleMessage(channel, message)
        );
    }

    handleMessage(channel, message) {
        console.log(`Message received. Channel: ${channel}. Message: ${message}.`);
    }
}

const testPubSub = new PubSub();

testPubSub.publisher.publish(CHANNELS.TEST, 'foo');

validating transaction data bug

I found that validTransactionData method of Blockchain class does not work properly.

Precisely I think that this part is problem

      const trueBalance = Wallet.calculateBalance({
        chain: this.chain,
        address: transaction.input.address
      });

      if (transaction.input.amount !== trueBalance) {
        console.error('Invalid input amount');
        return false;
      }

Here you are comparing for every transaction's input amount with true balance of its sender. True balance will always be same for one wallet on blockchain but transaction.input.amount can be different for every transaction. So here is the problem that I faced when i tried to broadcast my blockchain to other nodes in the network, they wouldn't accept it becouse they marked it as invalid.
validTransactionData always outputs 'Invalid input amount' error.
So my fix is - only calculate balance of the wallet from start of blockchain up to this block transaction - this.chain.slice(0,i)

          const trueBalance = Wallet.calculateBalance({
            chain: this.chain.slice(0,i),
            address: transaction.input.address
          });

          if (transaction.input.amount !== trueBalance) {
            console.error('Invalid input amount');
            return false;
          }

I've tested it and it works perfectly

Hey I am getting "TypeError: Cannot read property 'publicKey' of undefined" on calling get request in NodeJS project.

Full Error message is below..

C:\Users\Education Use\crypto\app\pubsub.js:66
                            inputAddress: this.wallet.publicKey
                                                      ^

TypeError: Cannot read property 'publicKey' of undefined
    at Object.message (C:\Users\Education Use\crypto\app\pubsub.js:66:55)
    at C:\Users\Education Use\crypto\node_modules\pubnub\lib\core\components\listener_manager.js:70:40
    at Array.forEach (<anonymous>)
    at _default.announceMessage (C:\Users\Education Use\crypto\node_modules\pubnub\lib\core\components\listener_manager.js:69:23)
    at C:\Users\Education Use\crypto\node_modules\pubnub\lib\core\components\subscription_manager.js:712:35
    at Array.forEach (<anonymous>)
    at _default._processSubscribeResponse (C:\Users\Education Use\crypto\node_modules\pubnub\lib\core\components\subscription_manager.js:579:16) 
    at onResponse (C:\Users\Education Use\crypto\node_modules\pubnub\lib\core\components\endpoint.js:252:7)
    at C:\Users\Education Use\crypto\node_modules\pubnub\lib\networking\modules\web-node.js:100:12
    at Request.callback (C:\Users\Education Use\crypto\node_modules\superagent\lib\node\index.js:716:12)

I am using PubNub Application and below is the pubsub.js file:

const PubNub = require('pubnub');

const credentials = {
    publishKey: 'pub-c-80cb1b82-bec3-46ec-bd1d-5ecfbdc7b268',
    subscribeKey: 'sub-c-9246a854-b768-11ea-bf7c-ae6a3e72d19d',
    secretKey: 'sec-c-YTA3ZmIwODYtNTI3Ni00ZWVkLWI0ZDYtMTlmY2QyNzM2Mzg0'
};

const CHANNELS = {
    TEST: 'TEST',
    BLOCKCHAIN: 'BLOCKCHAIN',
    TRANSACTION: 'TRANSACTION'
};

class PubSub{
    constructor({ blockchain, transactionPool }) {
        this.blockchain = blockchain;
        this.transactionPool = transactionPool;
        // this.wallet = wallet;
    
        this.pubnub = new PubNub(credentials);

        this.pubnub.subscribe({ channels: [Object.values(CHANNELS)] });

        this.pubnub.addListener(this.listener());
    }

    broadcastChain() {
        this.publish({
            channel: CHANNELS.BLOCKCHAIN,
            message: JSON.stringify(this.blockchain.chain)
        });
    }

    broadcastTransaction(transaction) {
        this.publish({
            channel: CHANNELS.TRANSACTION,
            message: JSON.stringify(transaction)
        });
    }

    subscribeToChannels() {
        this.pubnub.subscribe({
            channels: [Object.values(CHANNELS)]
        });
    }

    listener() {
        return {
            message: messageObject => {
                const { channel, message } = messageObject;
                
                console.log(`Message received. Channel: ${channel}. Message: ${message}`);
                const parsedMessage = JSON.parse(message);
                
                switch(channel) {
                    case CHANNELS.BLOCKCHAIN:
                        this.blockchain.replaceChain(parsedMessage, true, () => {
                            this.transactionPool.clearBlockchainTransactions(
                                { chain: parsedMessage.chain }
                            );
                        });
                        break;
                    case CHANNELS.TRANSACTION:
                        if (!this.transactionPool.existingTransaction({
                            inputAddress: this.wallet.publicKey
                        })) {
                            this.transactionPool.setTransaction(parsedMessage);
                        }
                        break;
                    default:
                        return;
                }
            }
        }
    }   
    
    publish({ channel, message }) {
    // there is an unsubscribe function in pubnub
    // but it doesn't have a callback that fires after success
    // therefore, redundant publishes to the same local subscriber will be accepted as noisy no-ops
    this.pubnub.publish({ message, channel });
    }

    broadcastChain() {
        this.publish({
            channel: CHANNELS.BLOCKCHAIN,
            message: JSON.stringify(this.blockchain.chain)
        });
    }
    
    broadcastTransaction(transaction) {
        this.publish({
            channel: CHANNELS.TRANSACTION,
            message: JSON.stringify(transaction)
        });
    }
}

module.exports = PubSub;

What can be the issue and how can I resolve this... please guide anyone.

TypeError: Cannot read properties of undefined (reading 'hash')

I'm on Chapter 3, I started getting this error in around section 15 and this failed error in test is not going away. I am now on section 18 in chapter 3. I have gone back to chapter 2 all sections trying to figure out if I missed something.

When I run test it shows this error that is not in the videos failed test:

TypeError: Cannot read properties of undefined (reading 'hash')
16 | static mineBlock({ lastBlock, data }) {
17 | const timestamp = Date.now();
18 | const lastHash = lastBlock.hash;
| ^
19 |
20 | return new this({
21 | timestamp,

at Function.mineBlock (block.js:18:32)
at Blockchain.addBlock (blockchain.js:9:32)
at Object. (blockchain.test.js:37:28)

The arrow on 18 in my command prompt points at the .hash in = lastBlock.hash.

If someone could help me figure out why my command prompt the tests can't read properties of hash?

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.