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

福尔摩斯对我笑 2019-03-01 36517 次 4175条

前言

正式了解比特币是在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
未来博客 博主大人
到了这个年纪,不应该再彷徨!

发表评论



 


已有 4175 条评论 1


  1. yeezy boost 350

    I wish to show my gratitude for your generosity in support of those who absolutely need help with the situation. Your very own dedication to getting the message all through had been incredibly good and has in most cases permitted most people just like me to arrive at their targets. Your amazing warm and helpful instruction denotes much a person like me and extremely more to my mates. Best wishes; from all of us.

    回复 2019年10月26日
  2. jordans

    I wanted to construct a small message to say thanks to you for some of the nice strategies you are posting here. My rather long internet search has now been paid with sensible facts to exchange with my company. I would tell you that many of us site visitors are rather endowed to be in a perfect place with many special professionals with beneficial hints. I feel really fortunate to have encountered your webpage and look forward to so many more awesome moments reading here. Thanks once more for everything.

    回复 2019年10月25日
  3. ultra boost

    My wife and i got absolutely lucky when Michael could deal with his inquiry by way of the ideas he acquired out of the web pages. It is now and again perplexing just to be releasing procedures which the others may have been selling. Therefore we consider we need the blog owner to give thanks to for that. Those illustrations you have made, the straightforward site menu, the friendships you give support to create – it is mostly unbelievable, and it is helping our son and us feel that the subject is fun, which is certainly wonderfully mandatory. Many thanks for everything!

    回复 2019年10月25日
  4. golden goose outlet

    Thank you a lot for providing individuals with an exceptionally nice opportunity to read in detail from this site. It is always so awesome and stuffed with a good time for me personally and my office colleagues to visit your website particularly three times every week to find out the new secrets you have got. Not to mention, I’m just certainly fulfilled with all the stunning knowledge you serve. Certain 2 facts on this page are surely the best I’ve had.

    回复 2019年10月25日
  5. adidas superstar

    I and my buddies ended up taking note of the nice thoughts from your web site and at once came up with a horrible suspicion I never thanked the web blog owner for those strategies. These women were definitely for this reason stimulated to read all of them and have now extremely been enjoying those things. Thank you for being simply kind and also for figuring out variety of high-quality subject areas most people are really needing to discover. My personal sincere apologies for not saying thanks to sooner.

    回复 2019年10月25日
  6. kyrie irving shoes

    Thanks a lot for giving everyone remarkably pleasant possiblity to read critical reviews from this blog. It is always very good and jam-packed with a great time for me and my office co-workers to visit your blog at least thrice every week to read the new things you will have. And indeed, I am at all times fulfilled concerning the cool creative ideas you give. Certain 3 facts in this posting are easily the simplest we have had.

    回复 2019年10月24日
  7. nike react

    A lot of thanks for all your valuable labor on this site. My mother really loves setting aside time for research and it is simple to grasp why. My spouse and i hear all about the dynamic method you give precious suggestions on this website and as well as increase participation from other people about this area so our own simple princess is understanding a great deal. Take advantage of the remaining portion of the year. You have been doing a fantastic job.

    回复 2019年10月24日
  8. jordan shoes

    I am also writing to make you know of the perfect discovery my friend’s princess found browsing your webblog. She came to understand such a lot of things, not to mention what it’s like to possess a great giving character to let other individuals easily gain knowledge of several very confusing matters. You truly surpassed my expectations. Many thanks for producing the great, dependable, informative and also cool tips about that topic to Julie.

    回复 2019年10月23日
  9. nike air max

    I truly wanted to send a remark in order to say thanks to you for these remarkable suggestions you are placing here. My considerable internet research has now been honored with incredibly good facts and strategies to talk about with my best friends. I would claim that we visitors are very blessed to exist in a remarkable place with so many outstanding people with valuable strategies. I feel very privileged to have seen the webpages and look forward to so many more brilliant minutes reading here. Thanks once again for all the details.

    回复 2019年10月22日
  10. vapormax

    I want to show some thanks to the writer just for bailing me out of this scenario. After researching through the internet and finding methods which were not pleasant, I figured my life was done. Being alive minus the approaches to the issues you have resolved by way of your entire post is a serious case, as well as those which may have negatively damaged my entire career if I hadn’t discovered your web page. Your actual natural talent and kindness in touching all the stuff was crucial. I’m not sure what I would have done if I had not come across such a thing like this. It’s possible to at this point look ahead to my future. Thanks for your time so much for this impressive and amazing guide. I will not think twice to recommend your web page to any person who wants and needs guide about this subject.

    回复 2019年10月21日
  11. supreme hoodie

    Thanks so much for giving everyone remarkably wonderful opportunity to read in detail from here. It’s always so lovely and as well , full of a great time for me and my office acquaintances to visit your blog minimum 3 times every week to study the fresh issues you will have. And definitely, we are always fascinated with the remarkable guidelines you serve. Some 4 tips in this posting are unequivocally the most impressive we have all had.

    回复 2019年10月20日
  12. curry 6

    I want to express thanks to the writer for rescuing me from such a difficulty. As a result of browsing throughout the world-wide-web and finding concepts that were not powerful, I thought my entire life was well over. Living devoid of the strategies to the issues you’ve fixed as a result of your article content is a crucial case, as well as those that could have negatively damaged my career if I had not come across your site. Your main knowledge and kindness in controlling a lot of things was very useful. I’m not sure what I would have done if I hadn’t come upon such a thing like this. It’s possible to at this moment look ahead to my future. Thanks a lot very much for your expert and results-oriented help. I won’t think twice to propose your site to anyone who desires guidance about this matter.

    回复 2019年10月19日
  13. kd shoes

    I wanted to write down a quick comment to appreciate you for those great ways you are writing on this site. My extensive internet lookup has now been paid with awesome suggestions to talk about with my partners. I ‘d assert that many of us visitors are truly fortunate to live in a great site with very many special people with insightful concepts. I feel really grateful to have used your webpages and look forward to plenty of more fabulous times reading here. Thanks a lot once again for a lot of things.

    回复 2019年10月18日
  14. adidas nmd

    Thanks so much for giving everyone an exceptionally marvellous chance to read critical reviews from this blog. It can be so sweet plus jam-packed with a lot of fun for me personally and my office mates to visit your site really three times every week to read the new items you have got. And definitely, I am also always fascinated with all the outstanding techniques served by you. Certain 1 ideas in this article are really the most suitable I’ve had.

    回复 2019年10月17日
  15. yeezy boost 350 v2

    My spouse and i have been very glad Emmanuel could deal with his homework through the entire precious recommendations he received out of the web site. It’s not at all simplistic to just happen to be making a gift of procedures most people might have been selling. And we also do understand we have got the writer to appreciate for that. All of the explanations you have made, the straightforward web site menu, the friendships you can make it easier to instill – it’s many remarkable, and it’s facilitating our son and us reason why that content is amusing, and that’s truly serious. Thanks for everything!

    回复 2019年10月16日
  16. christian louboutin shoes

    I simply wanted to say thanks yet again. I do not know the things I would’ve followed without the entire smart ideas shared by you directly on this problem. It absolutely was a real scary situation in my view, but taking a look at a specialized style you resolved the issue took me to leap with gladness. I’m happy for this help and in addition hope that you know what a great job you are accomplishing training most people thru your websites. I am sure you haven’t got to know any of us.

    回复 2019年10月16日
  17. nike air max 95

    I definitely wanted to compose a small remark so as to appreciate you for all the amazing guides you are giving out on this site. My considerable internet research has at the end been honored with reputable facts and techniques to talk about with my friends and family. I would repeat that we website visitors actually are undoubtedly lucky to exist in a fine network with so many brilliant professionals with good things. I feel very grateful to have discovered your webpages and look forward to tons of more excellent minutes reading here. Thank you once more for all the details.

    回复 2019年10月15日
  18. yeezy 500 blush

    My wife and i were contented when Raymond could finish up his homework through the precious recommendations he acquired from your very own web pages. It’s not at all simplistic to simply find yourself releasing methods that some people might have been selling. We consider we’ve got the website owner to be grateful to for that. All of the explanations you made, the easy web site menu, the relationships you assist to instill – it’s got most extraordinary, and it’s letting our son and the family believe that this idea is exciting, which is especially mandatory. Many thanks for all!

    回复 2019年10月14日
  19. jordan shoes

    I and also my guys ended up checking the best advice on your web site and unexpectedly came up with a horrible feeling I had not thanked the blog owner for those tips. All of the young men appeared to be for that reason excited to read through them and now have absolutely been using these things. We appreciate you genuinely considerably thoughtful as well as for obtaining this sort of exceptional themes most people are really needing to know about. My sincere regret for not saying thanks to sooner.

    回复 2019年10月13日
  20. birkin bag

    Thanks so much for giving everyone such a terrific chance to read in detail from here. It’s usually so great and also full of fun for me and my office friends to search your site a minimum of thrice in a week to read the new items you will have. And definitely, we are actually impressed considering the astonishing concepts you serve. Some 3 areas on this page are completely the most efficient I have had.

    回复 2019年10月12日
  21. ferragamo belts

    I would like to show my appreciation to this writer just for rescuing me from this particular situation. Just after searching throughout the search engines and obtaining ideas which were not powerful, I was thinking my life was done. Living minus the answers to the issues you’ve sorted out through your good guideline is a critical case, as well as those that could have in a negative way affected my entire career if I hadn’t encountered your blog. Your mastery and kindness in maneuvering a lot of stuff was tremendous. I’m not sure what I would have done if I hadn’t discovered such a point like this. It’s possible to at this time relish my future. Thanks for your time very much for this reliable and result oriented guide. I will not think twice to endorse your web blog to anybody who ought to have guidelines about this subject.

    回复 2019年10月11日
  22. yeezy shoes

    Needed to send you a very little observation so as to say thanks a lot as before for your personal awesome things you have documented on this page. This has been certainly tremendously generous with people like you to make freely all a few people could have made available as an e book to earn some dough for themselves, chiefly seeing that you could have tried it in case you considered necessary. These solutions additionally served to become great way to understand that other individuals have the identical dream like my own to know the truth significantly more in regard to this condition. Certainly there are thousands of more pleasurable opportunities in the future for many who discover your blog post.

    回复 2019年10月10日
  23. nike kyrie 5

    Thank you for your own effort on this website. Kim takes pleasure in getting into internet research and it’s easy to understand why. My partner and i notice all regarding the compelling way you convey functional things via your web blog and even boost response from people on that theme then our favorite princess is truly becoming educated a great deal. Take advantage of the rest of the year. You have been conducting a first class job.

    回复 2019年10月9日
  24. balenciaga shoes

    I really wanted to type a small comment to be able to say thanks to you for these stunning strategies you are writing at this site. My extensive internet search has at the end been paid with wonderful facts and techniques to talk about with my partners. I ‘d claim that most of us readers actually are really blessed to exist in a wonderful community with many wonderful professionals with valuable solutions. I feel quite fortunate to have come across your entire web site and look forward to plenty of more fabulous moments reading here. Thanks a lot again for all the details.

    回复 2019年10月8日
  25. nike air max

    I simply desired to thank you very much once again. I am not sure the things I could possibly have accomplished without the type of basics shared by you directly on such industry. Completely was the intimidating issue in my position, but finding out your specialized manner you solved the issue forced me to jump with gladness. Now i’m grateful for the information as well as trust you are aware of an amazing job you are carrying out teaching people by way of your blog post. I am sure you’ve never encountered any of us.

    回复 2019年10月8日