Node.js实现一个超级简便的挖矿功能

福尔摩斯对我笑 2019-03-01 3616 次 675条

前言

正式了解比特币是在17年的时候,在那个闭着眼睛都能赚到钱的年代,我也跟绝大多数人一样,进入了这场声势浩大的"赌博"。

“赌博”过程中让我对区块链产生了兴趣,我很好奇,他们经常提到的挖矿是什么?挖矿为啥就费电,费CPU?

所谓的挖矿

后来查资料才了解到,挖矿就是不断的计算,并且是毫无道理的“瞎算”,只要达到一个很“傻”的条件就表示你挖矿成功。

Node实现简单的挖矿

const crypto = require('crypto');

//创世区块 这是第一次挖矿生成的数据
const initBlock ={ 
    index: 0,
    nonce: 1307,
    data: '我是创世区块',
    prevHash: 0,
    timestamp: 1551248147024,
    hash:
     '00e275e4946f0fdf672be32fd4dfeaae0b7efd8d9f377c48ac510efe79d6a814' 
    };

class Blockchain{
    constructor(){
        this.blockchain = [
            initBlock //默认有一个创世区块
        ];
        this.data= [];
        this.difficulty = 2; //难度
        
    }

    //挖矿
    min(){
        const index = this.blockchain.length; //索引.也就是现在区块的长度
        let nonce = 0; //随机数
        const data = this.data;
        const prevHash= this.getLastChain();// 上一个区块的hash值
        let timestamp = new Date().getTime(); //时间戳

        let hash = this.computeHash(index,prevHash,timestamp,data, nonce);
        //判断得到的hash的前 几位 是否为 0~
        while(hash.slice(0, this.difficulty) !== "0".repeat( this.difficulty ))
        {
            nonce+=1;
            hash = this.computeHash(index,prevHash,timestamp,data, nonce);
            console.log(`正在进行第${nonce}次挖矿:${hash}`);
        }
        this.blockchain.push({
            index,
            nonce,
            data,
            prevHash,
            timestamp,
            hash
        })
        console.log(this.blockchain);
            
    }   

    //获取最后一个区块的数据
    getLastChain(){
        return this.blockchain[this.blockchain.length-1].hash;
    }
    //计算哈希
    computeHash(index, prevHash, timestamp, data, nonce){
        return crypto
                .createHash('sha256')
                .update( index + prevHash + timestamp + data + nonce)
                .digest('hex');
    }

}


var chain = new Blockchain();
chain.min();

 

运行效果如下:

标签:

非特殊说明,本博所有文章均为博主原创。

头像也是LOGO
未来博客 博主大人
到了这个年纪,不应该再彷徨!

发表评论



 


已有 675 条评论 1


  1. SEO DC in Baltimore

    Very good article. I absolutely appreciate this site. Stick with it!

    回复 2020年2月26日
  2. tienda hippie madrid

    Dead composed subject material, appreciate it for entropy. “The earth was made round so we would not see too far down the road.” by Karen Blixen.

    回复 2020年2月26日
  3. Cornici per Mountain Bike

    Thanks for your concepts. One thing I’ve got noticed is banks in addition to financial institutions are aware of the spending behavior of consumers plus understand that most of the people max out there their real credit cards around the vacations. They smartly take advantage of this specific fact and begin flooding your own inbox and also snail-mail box by using hundreds of 0 APR credit cards offers immediately after the holiday season ends. Knowing that if you are like 98% in the American community, you’ll hop at the possible opportunity to consolidate consumer credit card debt and switch balances to 0 APR credit cards.

    回复 2020年2月26日
  4. supreme clothing

    I’m commenting to make you be aware of of the terrific experience my friend’s child undergone checking your site. She picked up so many things, which include what it’s like to have a very effective coaching mindset to have folks completely know precisely selected multifaceted issues. You really exceeded her expected results. I appreciate you for delivering such interesting, trustworthy, edifying and also unique tips about the topic to Sandra.

    回复 2020年2月26日
  5. Reddit soccer streams

    I was wondering if you ever thought of changing the layout of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or two pictures. Maybe you could space it out better?

    回复 2020年2月26日
  6. Abbruch Abbruch

    Hi, I do believe this is an excellent blog. I stumbledupon it 😉 I may revisit once again since I saved as a favorite it. Money and freedom is the best way to change, may you be rich and continue to help others.

    回复 2020年2月26日
  7. Gutter Company Raleigh NC

    I’m very pleased to find this web site. I want to to thank you for ones time for this wonderful read!! I definitely savored every part of it and I have you bookmarked to see new things in your website.

    回复 2020年2月26日
  8. Ontario Lottery

    Everything is very open with a clear description of the challenges. It was really informative. Your site is very helpful. Thank you for sharing!

    回复 2020年2月25日
  9. modern construction management

    Do you have a spam issue on this site; I also am a blogger, and I was wondering your situation; we have developed some nice practices and we are looking to trade methods with other folks, be sure to shoot me an e-mail if interested.

    回复 2020年2月25日
  10. Website

    I seriously love your blog.. Excellent colors & theme. Did you develop this web site yourself? Please reply back as I’m attempting to create my very own site and would love to find out where you got this from or what the theme is named. Cheers!

    回复 2020年2月25日
  11. Kimcycle 回复 2020年2月25日
  12. junk removal Raleigh

    Spot on with this write-up, I honestly think this web site needs far more attention. I’ll probably be returning to read more, thanks for the info.

    回复 2020年2月25日
  13. Best egusi soup in La

    It’s hard to find educated people for this topic, but you sound like you know what you’re talking about! Thanks

    回复 2020年2月25日
  14. here

    Having read this I thought it was extremely informative. I appreciate you finding the time and effort to put this short article together. I once again find myself spending way too much time both reading and leaving comments. But so what, it was still worth it!

    回复 2020年2月25日
  15. cleaning services

    Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You obviously know what youre talking about, why waste your intelligence on just posting videos to your site when you could be giving us something informative to read?

    回复 2020年2月25日
  16. motherhood and work life

    Hi, I think your site might be having browser compatibility issues. When I look at your blog site in Chrome, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, wonderful blog!

    回复 2020年2月25日
  17. source

    I love looking through a post that can make men and women think. Also, many thanks for allowing me to comment.

    回复 2020年2月25日
  18. cheap beverages

    My brother suggested I might like this website. He was totally right. This post truly made my day. You cann’t imagine just how much time I had spent for this information! Thanks!

    回复 2020年2月25日
  19. superb maids discount code

    Thanks for your marvelous posting! I genuinely enjoyed reading it, you could be a great author.I will remember to bookmark your blog and will come back at some point. I want to encourage yourself to continue your great job, have a nice day!

    回复 2020年2月24日
  20. source

    I quite like looking through an article that can make men and women think. Also, thank you for allowing for me to comment.

    回复 2020年2月24日
  21. source

    Good article! We will be linking to this particularly great post on our website. Keep up the great writing.

    回复 2020年2月24日
  22. Bed assembly service

    I believe you have mentioned some very interesting details , appreciate it for the post.

    回复 2020年2月24日
  23. polsterei düsseldorf

    you will have an amazing blog here! would you prefer to make some invite posts on my blog?

    回复 2020年2月24日
  24. golden goose sneakers

    My wife and i ended up being very comfortable Raymond could complete his preliminary research out of the precious recommendations he came across through the web pages. It is now and again perplexing to just possibly be offering guidance that people have been making money from. We discover we’ve got you to thank for this. All the illustrations you made, the simple website navigation, the relationships your site help to engender – it’s got mostly overwhelming, and it is leading our son and us reckon that that theme is exciting, which is certainly pretty important. Thanks for all the pieces!

    回复 2020年2月23日
  25. Placenta benefits

    That is a good tip particularly to those new to the blogosphere. Short but very precise information… Appreciate your sharing this one. A must read article!

    回复 2020年2月23日
  26. mobil bahis bedava bahis

    As a Newbie, I am constantly exploring online for articles that can be of assistance to me. Thank you

    回复 2020年2月23日
  27. betgram

    This is the fitting blog for anybody who needs to seek out out about this topic. You notice a lot its nearly hard to argue with you (not that I actually would need…HaHa). You definitely put a new spin on a subject thats been written about for years. Great stuff, simply great!

    回复 2020年2月23日
  28. super peach wear

    Great web site you have here.. It’s difficult to find high-quality writing like yours nowadays. I honestly appreciate people like you! Take care!!

    回复 2020年2月23日
  29. Tractor Workshop Manuals

    Top post Genachowski’s less than artful weaving of net neutrality and consumer privacy | Law and Politics of Broadband you’ve surely influenced all of us FYI have you read Middle East amazing headlines! Enjoy your day ! Flash Website Design

    回复 2020年2月23日
  30. mailing labels sticker

    Hi there! I just wish to give you a huge thumbs up for the great info you have here on this post. I am returning to your blog for more soon.

    回复 2020年2月23日
  31. cashdomino88.com/

    whoah this weblog is great i really like reading your articles. Keep up the great work! You realize, a lot of people are searching round for this info, you could help them greatly.

    回复 2020年2月22日
  32. Porn

    I’m not sure exactly why but this blog is loading extremely slow for me. Is anyone else having this problem or is it a issue on my end? I’ll check back later and see if the problem still exists.

    回复 2020年2月22日
  33. animation de logo

    Howdy! Someone in my Facebook group shared this site with us so I came to look it over. I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers! Fantastic blog and wonderful design and style.

    回复 2020年2月22日
  34. crazybulk avis

    I love reading through a post that will make people think. Also, many thanks for allowing for me to comment.

    回复 2020年2月22日
  35. Otto Cicione

    I found your this post while searching for information about blog-related research … It’s a good post .. keep posting and updating information. advice |

    回复 2020年2月22日
  36. CBD store near me

    Nice read, I just passed this onto a friend who was doing some research on that. And he just bought me lunch since I found it for him smile Thus let me rephrase that: Thanks for lunch!

    回复 2020年2月22日
  37. Virginia furniture assembly

    Excellent post. I was checking constantly this blog and I am impressed! Very helpful information particularly the last part 🙂 I care for such info much. I was seeking this particular information for a long time. Thank you and best of luck.

    回复 2020年2月22日
  38. DC Movers

    Thank you for all of the labor on this site. Kim enjoys engaging in investigation and it is obvious why. Many of us know all concerning the powerful manner you make vital things on this website and as well foster participation from other people on this situation and my girl is actually learning a whole lot. Take pleasure in the remaining portion of the year. You’re carrying out a useful job.

    回复 2020年2月22日
  39. male extra

    Wonderful post! We will be linking to this particularly great content on our website. Keep up the good writing.

    回复 2020年2月22日
  40. Buy Phone Battery Online

    Hey There. I found your weblog the usage of msn. This is a really smartly written article. I will be sure to bookmark it and come back to learn extra of your useful info. Thanks for the post. I’ll certainly return.

    回复 2020年2月21日
  41. Legal justice Advocates

    Next time I read a blog, I hope that it doesn’t fail me as much as this one. After all, Yes, it was my choice to read through, but I truly believed you would have something interesting to say. All I hear is a bunch of moaning about something you could fix if you were not too busy seeking attention.

    回复 2020年2月21日
  42. btl toys

    This is the perfect web site for everyone who really wants to find out about this topic. You understand so much its almost tough to argue with you (not that I personally will need to…HaHa). You certainly put a new spin on a topic which has been discussed for decades. Excellent stuff, just excellent.

    回复 2020年2月21日
  43. Vector Magic Crack

    Everyone loves it when folks get together and share ideas. Great website, keep it up!

    回复 2020年2月21日
  44. cheap nail products

    Hey there! I simply want to offer you a big thumbs up for your excellent information you’ve got here on this post. I’ll be coming back to your website for more soon.

    回复 2020年2月21日
  45. DMV braiders

    Hi there, I found your blog via Google while searching for a related topic, your site came up, it looks good. I’ve bookmarked it in my google bookmarks.

    回复 2020年2月21日
  46. Virginia Furniture installers

    Pretty great post. I simply stumbled upon your blog and wanted to say that I have truly loved browsing your blog posts. In any case I will be subscribing in your feed and I hope you write once more soon!

    回复 2020年2月21日
  47. DC Furniture assembly

    Excellent post. I used to be checking continuously this blog and I am impressed! Extremely helpful info specially the ultimate part 🙂 I handle such information a lot. I was seeking this certain information for a very lengthy time. Thanks and good luck.

    回复 2020年2月21日
  48. Teocycle 回复 2020年2月20日