0


Web3.0:重新定义互联网的未来

在这里插入图片描述

💗wei_shuo的个人主页

💫wei_shuo的学习社区

🌐Hello World !


Web3.0:重新定义互联网的未来

Web3.0是指下一代互联网,也称为“分布式互联网”。相比于Web1.0和Web2.0,Web3.0具有更强的去中心化、智能化和安全性。目前,Web3.0正在快速发展,为互联网的未来带来了无限可能

Web3.0的核心特点是去中心化。在传统的互联网中,用户与服务提供商之间的关系是单向的,服务提供商掌握了用户的数据和信息。而在Web3.0中,用户可以通过去中心化的方式掌握自己的数据和信息,不再被服务提供商所控制

智能合约

智能合约是Web3.0的重要组成部分。智能合约是一种基于区块链技术的自动化合约,它可以自动执行并验证合约中的条款。智能合约的出现使得合约的执行更加高效、便捷和安全

下面是一个简单的智能合约实例:

pragma solidity ^0.4.0;

contract HelloWorld {
   string public message;

   function HelloWorld(string initMessage) {
       message = initMessage;
   }

   function setMessage(string newMessage) {
       message = newMessage;
   }
}

这个智能合约可以让用户设置一个消息,并且其他用户可以查看这个消息。通过智能合约,用户可以在没有中间人的情况下进行交互

区块链技术

区块链是Web3.0的核心技术之一。它是一种去中心化的、不可篡改的分布式账本技术,可以记录交易、资产和权益等信息。区块链技术的安全性和透明度使其成为了Web3.0的重要基础;在区块链技术中,每个区块都包含了前一个区块的哈希值,这样就形成了一条不可篡改的链。通过这种方式,区块链技术可以有效地防止数据篡改和欺诈行为,从而保证了数据的安全性和可靠性

// 创建一个区块classBlock{constructor(index, timestamp, data, previousHash){this.index = index;this.timestamp = timestamp;this.data = data;this.previousHash = previousHash;this.hash =this.calculateHash();}calculateHash(){returnSHA256(this.index +this.timestamp +this.data +this.previousHash).toString();}}// 创建一个区块链classBlockchain{constructor(){this.chain =[this.createGenesisBlock()];}createGenesisBlock(){returnnewBlock(0,newDate(),"Genesis Block","0");}getLatestBlock(){returnthis.chain[this.chain.length -1];}addBlock(newBlock){
    newBlock.previousHash =this.getLatestBlock().hash;
    newBlock.hash = newBlock.calculateHash();this.chain.push(newBlock);}isValid(){for(let i =1; i <this.chain.length; i++){const currentBlock =this.chain[i];const previousBlock =this.chain[i -1];if(currentBlock.hash !== currentBlock.calculateHash()){returnfalse;}if(currentBlock.previousHash !== previousBlock.hash){returnfalse;}}returntrue;}}// 创建一个区块链实例const blockchain =newBlockchain();// 添加新的区块
blockchain.addBlock(newBlock(1,newDate(),{ amount:100}));
blockchain.addBlock(newBlock(2,newDate(),{ amount:200}));// 验证区块链是否有效
console.log("Is blockchain valid? "+ blockchain.isValid());

去中心化应用程序(DApps)

去中心化应用程序(DApps)是Web3.0的另一个重要技术。它们是基于区块链技术构建的应用程序,可以在没有中心化服务器的情况下运行。DApps具有更高的安全性和透明度,可以为用户提供更好的隐私保护和数据安全

// 创建一个简单的DAppsconst DApps ={
  state:{
    count:0},
  mutations:{increment(state){
      state.count++;}},
  actions:{increment(context){
      context.commit("increment");}}};// 创建一个Vue实例const app =newVue({
  el:"#app",
  data:{
    count:0},
  methods:{increment(){this.count++;}}});// 将DApps与Vue实例进行绑定
Vuex.Store(DApps);
Vue.use(Vuex);// 在Vue实例中使用DApps
app.$store.dispatch("increment");

加密货币

加密货币是Web3.0的另一个重要技术。它们是基于区块链技术构建的数字货币,可以在全球范围内进行安全、快速、便捷的交易。加密货币使用密码学技术来保证交易的安全性和可靠性

// 创建一个简单的加密货币classCryptoCurrency{constructor(){this.chain =[this.createGenesisBlock()];this.difficulty =4;}createGenesisBlock(){returnnewBlock(0,newDate(),"Genesis Block","0");}getLatestBlock(){returnthis.chain[this.chain.length -1];}addBlock(newBlock){
    newBlock.previousHash =this.getLatestBlock().hash;
    newBlock.mineBlock(this.difficulty);this.chain.push(newBlock);}isValid(){for(let i =1; i <this.chain.length; i++){const currentBlock =this.chain[i];const previousBlock =this.chain[i -1];if(currentBlock.hash !== currentBlock.calculateHash()){returnfalse;}if(currentBlock.previousHash !== previousBlock.hash){returnfalse;}}returntrue;}}// 创建一个简单的加密货币交易classTransaction{constructor(fromAddress, toAddress, amount){this.fromAddress = fromAddress;this.toAddress = toAddress;this.amount = amount;}}// 创建一个简单的区块classBlock{constructor(index, timestamp, data, previousHash){this.index = index;this.timestamp = timestamp;this.data = data;this.previousHash = previousHash;this.nonce =0;this.hash =this.calculateHash();}calculateHash(){returnSHA256(this.index +this.timestamp +this.data +this.previousHash +this.nonce).toString();}mineBlock(difficulty){while(this.hash.substring(0, difficulty)!==Array(difficulty +1).join("0")){this.nonce++;this.hash =this.calculateHash();}}}// 创建一个加密货币实例const cryptoCurrency =newCryptoCurrency();// 创建一个交易const transaction =newTransaction("address1","address2",100);// 添加新的交易
cryptoCurrency.addBlock(newBlock(1,newDate(),{ transaction }));// 验证加密货币是否有效
console.log("Is cryptoCurrency valid? "+ cryptoCurrency.isValid());

web3.0程序

Solidity编写智能合约并与以太坊区块链进行交互,实现了一个简单的投票系统

智能合约:

pragma solidity ^0.4.24;

contract Voting {
    // 候选人结构体
    struct Candidate {
        string name;
        uint voteCount;
    }

    // 候选人数组
    Candidate[] public candidates;

    // 投票人地址到投票状态的映射
    mapping(address => bool) public voters;

    // 添加候选人
    function addCandidate(string _name) public {
        candidates.push(Candidate(_name, 0));
    }

    // 投票
    function vote(uint _candidateIndex) public {
        // 如果已经投过票,则抛出异常
        require(!voters[msg.sender]);

        // 如果候选人不存在,则抛出异常
        require(_candidateIndex < candidates.length);

        // 修改投票人状态为已投票
        voters[msg.sender] = true;

        // 候选人得票数加1
        candidates[_candidateIndex].voteCount++;
    }

    // 获取候选人数量
    function getCandidateCount() public view returns (uint) {
        return candidates.length;
    }

    // 获取候选人信息
    function getCandidate(uint _index) public view returns (string, uint) {
        return (candidates[_index].name, candidates[_index].voteCount);
    }
}

智能合约实现了以下功能:

  • 添加候选人
  • 投票
  • 获取候选人数量
  • 获取候选人信息

前端页面中,可以通过调用智能合约的方法来实现投票系统的功能

<!DOCTYPE html><html><head><title>Voting System</title><metacharset="utf-8"><scriptsrc="./web3.min.js"></script><scriptsrc="./abi.js"></script><script>var contractAddress ="0x1234567890abcdef1234567890abcdef12345678";var contractABI = abi;// 从abi.js中获取智能合约ABIvar contract;functioninit(){if(typeof web3 !=='undefined'){
                web3 =newWeb3(web3.currentProvider);}else{alert("Please install MetaMask.");}

            contract =newweb3.eth.Contract(contractABI, contractAddress);}functionaddCandidate(){var name = document.getElementById("candidateName").value;

            contract.methods.addCandidate(name).send({from: web3.eth.defaultAccount}).then(function(){alert("Candidate added.");});}functionvote(){var candidateIndex = document.getElementById("candidateIndex").value;

            contract.methods.vote(candidateIndex).send({from: web3.eth.defaultAccount}).then(function(){alert("Voted successfully.");});}functiongetCandidateCount(){
            contract.methods.getCandidateCount().call().then(function(count){
                    document.getElementById("candidateCount").innerHTML = count;});}functiongetCandidate(){var candidateIndex = document.getElementById("candidateIndex2").value;

            contract.methods.getCandidate(candidateIndex).call().then(function(result){
                    document.getElementById("candidateInfo").innerHTML = result[0]+": "+ result[1]+" votes";});}</script></head><bodyonload="init()"><h1>Voting System</h1><h2>Add Candidate</h2><inputtype="text"id="candidateName"placeholder="Candidate Name"><br><buttononclick="addCandidate()">Add</button><h2>Vote</h2><inputtype="text"id="candidateIndex"placeholder="Candidate Index"><br><buttononclick="vote()">Vote</button><h2>Get Candidate Count</h2><buttononclick="getCandidateCount()">Get Count</button><divid="candidateCount"></div><h2>Get Candidate Info</h2><inputtype="text"id="candidateIndex2"placeholder="Candidate Index"><br><buttononclick="getCandidate()">Get Info</button><divid="candidateInfo"></div></body></html>

前端页面通过调用智能合约的方法实现了以下功能:

  • 添加候选人
  • 投票
  • 获取候选人数量
  • 获取候选人信息

使用Web3.js与以太坊区块链交互时,需要先安装MetaMask插件并登录账户,否则无法使用

总结

Web3.0是下一代互联网的技术架构,它将互联网的功能扩展到了一个全新的层次。Web3.0的核心技术包括区块链、智能合约、去中心化应用程序(DApps)和加密货币等。这些技术为Web3.0提供了更大的安全性、透明度和可扩展性,使它成为下一代互联网的有力推动者


🌼 结语:创作不易,如果觉得博主的文章赏心悦目,还请——

点赞

👍

收藏

⭐️

评论

📝


在这里插入图片描述

标签: web3 区块链

本文转载自: https://blog.csdn.net/weixin_62765017/article/details/130285187
版权归原作者 wei_shuo 所有, 如有侵权,请联系我们删除。

“Web3.0:重新定义互联网的未来”的评论:

还没有评论