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

福尔摩斯对我笑 2019-03-01 19753 次 2492条

前言

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

发表评论



 


已有 2492 条评论 1


  1. air jordans

    My spouse and i ended up being really excited Michael could round up his basic research using the precious recommendations he gained when using the site. It is now and again perplexing to simply always be handing out steps that a number of people might have been making money from. We really figure out we now have the blog owner to give thanks to for that. The entire illustrations you made, the easy blog menu, the friendships you will help to promote – it’s all remarkable, and it’s really letting our son and our family imagine that this matter is satisfying, which is certainly exceedingly fundamental. Thanks for all!

    回复 2019年10月30日
  2. jordan shoes

    I wish to show my gratitude for your kind-heartedness for women who must have assistance with this important subject. Your special commitment to getting the message all-around appears to be pretty interesting and has specifically empowered some individuals just like me to arrive at their aims. Your entire important facts can mean a great deal a person like me and extremely more to my office workers. Thanks a lot; from each one of us.

    回复 2019年10月30日
  3. off white shoes

    I precisely wished to thank you very much once more. I do not know what I would have used in the absence of the type of creative concepts shared by you on that topic. It absolutely was the frustrating crisis in my opinion, nevertheless being able to see this specialized style you handled that made me to leap with fulfillment. I am happier for this service and even wish you find out what a great job you are always carrying out training most people via your site. I know that you have never met any of us.

    回复 2019年10月30日
  4. kobe shoes

    I wanted to write a message to thank you for all the lovely suggestions you are sharing at this website. My time intensive internet lookup has finally been compensated with extremely good details to share with my friends. I ‘d point out that most of us website visitors actually are unquestionably lucky to dwell in a good website with very many lovely people with insightful principles. I feel very much privileged to have seen your web page and look forward to really more fun times reading here. Thanks once again for everything.

    回复 2019年10月30日
  5. nike lebron 15

    Thanks so much for giving everyone an exceptionally marvellous opportunity to read from this blog. It’s usually very useful and also jam-packed with amusement for me personally and my office acquaintances to search your site minimum 3 times in one week to read through the fresh things you have got. And indeed, I’m also certainly astounded considering the fantastic knowledge served by you. Certain 3 areas in this post are really the very best we have ever had.

    回复 2019年10月29日
  6. golden goose sneakers

    I wish to express my thanks to you just for bailing me out of such a setting. After surfing through the world wide web and meeting methods which are not beneficial, I was thinking my life was over. Being alive minus the strategies to the issues you’ve sorted out by means of your guideline is a critical case, as well as the ones that might have in a wrong way affected my career if I hadn’t noticed your web blog. Your primary natural talent and kindness in handling everything was excellent. I don’t know what I would’ve done if I hadn’t come across such a solution like this. I am able to now look forward to my future. Thank you so much for your reliable and result oriented help. I won’t be reluctant to recommend your web blog to any person who will need guidance about this subject.

    回复 2019年10月29日
  7. supreme clothing

    My spouse and i got so glad when Louis could deal with his survey through the ideas he discovered out of your web site. It is now and again perplexing to just continually be giving out information and facts which often some others have been trying to sell. And we all grasp we need you to appreciate for that. All of the illustrations you have made, the simple web site navigation, the friendships you will help to foster – it’s got all powerful, and it is making our son in addition to our family believe that the matter is amusing, which is exceedingly indispensable. Many thanks for all the pieces!

    回复 2019年10月29日
  8. kyrie 3

    I’m writing to make you understand of the fantastic encounter my wife’s girl went through going through your web site. She mastered a wide variety of details, including what it’s like to have a great giving spirit to have many more with ease understand specific hard to do matters. You actually surpassed our own expectations. Thank you for presenting these essential, healthy, revealing as well as unique tips on this topic to Ethel.

    回复 2019年10月29日
  9. curry 6

    I wanted to make a small remark in order to thank you for some of the lovely tricks you are placing on this website. My extended internet look up has now been recognized with good facts to exchange with my great friends. I would assume that we site visitors actually are extremely endowed to live in a fabulous community with very many lovely individuals with valuable ideas. I feel somewhat blessed to have encountered your entire website and look forward to plenty of more fabulous times reading here. Thanks a lot once again for all the details.

    回复 2019年10月29日
  10. cheap nba jerseys

    My wife and i have been really joyous Raymond managed to deal with his researching out of the ideas he made out of the web site. It’s not at all simplistic to simply possibly be giving out tricks which often many others might have been selling. And we also do understand we have got the blog owner to give thanks to for this. The most important illustrations you made, the simple web site menu, the friendships you make it easier to create – it’s all astonishing, and it’s helping our son and our family reason why this subject is thrilling, which is certainly exceedingly vital. Many thanks for all the pieces!

    回复 2019年10月28日
  11. coach outlet online

    I intended to put you a very small note to say thanks a lot the moment again relating to the amazing things you’ve shown on this page. It’s quite open-handed with people like you to grant openly just what a few individuals would have supplied as an electronic book in order to make some money on their own, specifically since you might have tried it in the event you desired. Those good tips likewise acted as the fantastic way to fully grasp that the rest have similar dreams just as my very own to realize lots more with reference to this problem. I’m certain there are thousands of more fun occasions up front for people who read carefully your blog.

    回复 2019年10月28日
  12. supreme t shirt

    Thanks for each of your hard work on this web site. Gloria really likes managing internet research and it’s easy to understand why. Most of us hear all relating to the compelling tactic you offer great things by means of your web blog and as well strongly encourage participation from people on that area then my simple princess has been being taught a lot of things. Enjoy the rest of the new year. You’re the one performing a pretty cool job.

    回复 2019年10月28日
  13. jordan shoes

    I want to get across my respect for your kindness supporting people who require assistance with this one field. Your real dedication to getting the message all-around had become incredibly informative and has without exception enabled most people much like me to realize their objectives. Your new invaluable tutorial can mean so much to me and a whole lot more to my office workers. Many thanks; from everyone of us.

    回复 2019年10月27日
  14. timberlands

    My spouse and i felt so more than happy that Jordan managed to conclude his inquiry through the entire ideas he made out of the web pages. It’s not at all simplistic to just always be giving away solutions which often men and women have been trying to sell. So we recognize we have got you to thank because of that. The most important illustrations you’ve made, the easy blog menu, the relationships your site aid to engender – it’s got many wonderful, and it’s really leading our son and the family do think this theme is cool, which is rather indispensable. Thanks for everything!

    回复 2019年10月27日
  15. moncler outlet

    I truly wanted to jot down a small message to express gratitude to you for those amazing advice you are placing here. My extensive internet look up has now been recognized with reliable facts and techniques to talk about with my family members. I would admit that many of us website visitors are rather lucky to dwell in a wonderful network with very many outstanding professionals with great basics. I feel pretty privileged to have encountered the website and look forward to some more excellent minutes reading here. Thanks once again for a lot of things.

    回复 2019年10月26日
  16. yeezy shoes

    I have to point out my love for your kind-heartedness for individuals who must have help with in this concern. Your very own commitment to getting the message all around appears to be unbelievably helpful and have truly helped employees just like me to reach their endeavors. Your amazing invaluable useful information means so much to me and much more to my mates. Thank you; from each one of us.

    回复 2019年10月26日
  17. ralph lauren sale

    I’m also writing to make you understand of the terrific discovery our girl found visiting your web page. She came to find a good number of issues, most notably how it is like to have a great coaching nature to let a number of people effortlessly know precisely certain hard to do topics. You actually surpassed people’s expectations. Thank you for offering these useful, trustworthy, educational and fun thoughts on that topic to Jane.

    回复 2019年10月26日
  18. 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日
  19. 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日
  20. 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日
  21. 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日
  22. 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日
  23. 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日
  24. 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日
  25. 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日
  26. 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日
  27. 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日
  28. 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日
  29. 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日
  30. 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日
  31. 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日
  32. 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日
  33. 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日
  34. 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日
  35. 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日
  36. 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日
  37. 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日
  38. 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日
  39. 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日
  40. 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日
  41. 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日
  42. 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日