讨论共识算法、经济模型以及智能合约的开发

重磅发布 | Ultrain 2020 年技术路线图
B

Ultrain 主网于 2019.4.15 上线以来,已经稳定运行了一年的时间。目前 Ultrain 全网由近 700 个节点组成,节点分布在中国、美国东西海岸、澳大利亚、南非和德国等多个国家和地区,网络部署方式包括公有云网络(阿里云、亚马逊云、微软云、金山云)、企业内网、企业专网、公开互联网和家庭宽带网络的混合部署。

在技术稳定和成型的基础上,Ultrain 在 2020 年的主要任务是实现区块链技术在商业上的落地。在 2019 年下半年,我们花费了大量的精力与我们的众多商业合作伙伴进行商业模式的探索和设计,对区块链技术在商业竞争中的优劣势也有了充分的认识,具体可以见该文《区块链商业与技术现状与发展趋势展望》(深度好文:区块链商业与技术现状与发展趋势展望(上)、深度好文:区块链商业与技术现状与发展趋势展望(下))。在此基础上,我们确定了 2020 年希望通过 Ultrain 技术重点赋能的商业模式:在充分竞争的行业中,通过低成本建立互信的加盟制商业模式。

为实现这个目标,在 2020 年 Ultrian 的技术还需要从以下几个方面进一步升级:

符合商业合规要求:近几个月,各部委出台了区块链技术相关的规范指南,如央行颁布的《金融分布式账本技术安全规范》等。这些规范在后续将成为企业应用落地的基本门槛,为满足这些规范的要求,实现商业合规,Ultrain 需要在多个方面进行进一步的研发;

共识创新:加盟制商业模式有两个特点,一个是加盟商众多,一个是加盟商地域分布非常分散。这主要带来了多种技术挑战,包括加盟商的网络环境各异,需要让用户无感知的自动适配不同的网络;网络节点数量众多,加盟商的在线时间不固定,如何面对一个动态的网络维持区块链网络的稳定;做为一个开放式网络,如何保证网络的安全性;这些方面都是我们在今年需要解决的技术挑战;

区块链隐私保护:在商业环境下,隐私保护是系统运行的底线要求,央行在今年年初颁布的《个人金融信息保护技术规范》可以做为一个参考。Ultrain 在区块链隐私保护方案有深厚的积累,今年我们会形成商业化的解决方案对外输出并提供服务;

以上是 Ultrain 在 2020 年的三条技术路线,我们对该技术路线做了进一步的划分:

2020 年 Ultrain 技术路线图

以上就是Ultrain在2020年的技术路线图,其中包含了多个世界领先的技术突破。我们会在每个时间节点进一步公布技术实现的细节,与大家分享我们的进展。希望Ultrain在技术方面的突破能为区块链技术商业落地贡献自己的力量。

read more

关于区块链与币市的行业动态与最新消息

技术科普 | Ultrain 可编程零知识证明解决方案
Z

A保险公司希望向B医院购买某个年龄段的冠心病患者的相关数据用于该病种的保险精算分析,为了简化商业逻辑,我们假设患者的年龄信息是一个隐私数据福彩双色球,医院不能将其透露给保险公司,而保险公司需要取得年龄在40到90岁之间的患者的数据幸运飞艇,在这种情况下,区块链+零知识证明的解决方案,可以有效的支持该场景

read more

黑客马拉松与经常性的线下见面会或在线趣味游戏

珍惜别人善待自己_散文精选_心情随笔
Z

珍惜别人善待自己_散文精选_心情随笔
  退休了,很多时候是闲着的,人闲易,心闲则难。所以,就在不要去想以前被谁谁坑了,被某某压制了的那些陈年旧事。轻轻地闭着眼睛,静静的想想,我们这一生还真活的不容易。长身体的时候,遇到困难时期,野菜啊,槐树花啊什么的,我们那时就品尝够了。学习知识的黄金时代,又停课了,现在,明知道慢慢就会死去,还是在努力的活着,常常看朋友圈的养生之道。
  不管以前咋样,从现在开始,一定要学会珍惜别人。首先是要把以前坑过你,压过你的那些人,那些事统统忘掉。所以,珍惜别人不只是自己的亲人,自己的朋友,更重要的是要珍惜以前自己的敌人。只有原谅了他们的过错,才能彻底的解放你自己。自古至今,人类生存所依据的都是丛林法则,你只要想清楚了这一点,就能真正的解放自己了。
  谁也说不清楚,人活一辈子到底是为了什么。复杂的社会,看不透的人生,放不下的牵挂,经历不完的酸甜苦辣,其实,正是我们的这些麻辣的人生,让我们苦了、累了、彷徨了,才构成了整体的自己。若真正的缺失了,反倒还显得不够完美。所以,到了我们这个年龄,再忙也别忘了心疼心痛自己,一定要记得好好的照顾自己。人生如天气预报,预报是晴天,阳光灿烂,可转眼就风雨交加了。但是,不管是阳光灿烂,还是风雨交加。保持一份好心情,把握好每天的生活,照顾好自己独一无二的身体,就是最好的善待自己。得之坦然,失之泰然,顺其自然,随性而往,随遇而安,一切随缘,是我们现在最豁达,最明智的人生态度。
  只要是人,就都会有缺点的,那就彼此包容一点吧。我们也都是有优点的,那就彼此欣赏一点吧。我们都有个性的,那就彼此谦让一点吧。我们的思维都是有差异的,那就彼此接纳一点吧。我们都有自己的伤心,那就彼此安慰一点吧。我们都是有快乐的,那就彼此分享一点吧。放下所有的恩恩怨怨,放下任性,放下嫉妒,折掉自己的有色眼镜。因为我们有缘相识,请珍惜生命中的每一位家人、同事、同学、老师与朋友。开心的过好每一天!
  十年后,你仍保持了健康的体魄,还能到处旅游、打拳、跳舞等等什么的。您的孩子一定的会说,老爸老妈你们太明智了。我们能给孩子最好的礼物,是自己的健康。嘻嘻,唠叨一点,这样重要的事情,我就再说一遍吧,请大家记住这一句话。给你孩子最好的礼物,是保持好自己的身心健康。
  其实,我们一生只要做好两件事就行了,第一是教育好自己的孩子。孩子有的会成为天才,有的会成为人才,这时属于成才类,是我们理想的子女类型。但是,最起码是要让孩子成气,不要危害社会。我们作为孩子的第一任老师,对孩子来说是非常重要的。尽管有人的孩子坐牢了,有人的孩子被处决了。但是,到了我们这个年龄,这个任务终究算是已经完成了,谁也没办法再来第二次。第二是要照顾好自己,老了别拖累自己的孩子。
  毫无疑问,再过若干年,我们都将离开这里。对于这个世界来说,我们将彻底的变成虚无。我们奋斗了一生,带不走一草一木。我们执着了一生,带不走一分虚荣及爱慕。说白了,就是你怎么来的,还是得怎么离去!总有那么一天,我们都要走到那最后一步的。假如你到了天国或地狱,蓦然回首,会发现我们的这一生,形同虚无,包括那些将相王侯,亦是如此,就像我以前写的那首诗手一样:“周秦汉,元明清,先帝去,后皇跟。将相孤冢立荒野,草民仍旧是草民。”
  所以,从现在起,我们要用心生活,天天开心快乐。优秀的也好,平庸的也罢,弹指一挥,百年即逝,都将不过是一捧黄土而已。所以,要善待自己身边的每一个人,所谓的缘分,所谓的下辈子,那肯定是未知数,谁也说不清楚。一辈子真的好短,好短哦。有多少人说好的要过一辈子,可走着走着就只剩下了曾经。又有多少人说好的要做一辈子的朋友,可转身就成为了最熟悉的陌生人。还有的挥手告别的时候,彩票说好明天再见的,可醒来却是天各一方了。
  人生一世,草木一秋,原本是一场空的。何必处处计较,寸步不让呢。话多伤了别人,恨多伤了自身。与其伤人又伤身,还不如放眼看世界,心一宽了事。人一辈子就图个问心无愧,悠然自在。世间的理争不完,还不一定争得了,何苦呢!
  你自己的心幸福了,日子才能轻松。想的太多了,是容易烦恼的福彩双色球。你在乎的太多,就容易困扰幸运飞艇。你追求太多了,没有不累倒的。好好珍惜身边的人吧,因为所谓的来生缘,那是未知的。好好感感悟你生活的快乐吧,因为转瞬就将逝去。好好善待自己,对自己放松一点,不要苛求。好好去享受你的每一天,把今生的日子过好

read more

链上分布式应用的开发工具以及高质量的应用推荐

新版Ultrain浏览器上线,终于可以查Token啦!
I

Ultrain测试网上线后,很多开发者尝试写了合约,并用Ultrain浏览器进行了合约的部署操作。其中最热门的就是发Token合约,大家也想亲身体验发Token的快感!连Ultrain团队的的好几个程序员都迫不及待地进行创建账户、申请资源、写合约、部署合约、调用合约等一系列流程,尝试发Token。

可是操作完,大家向产品经理抱怨:通过「超脑浏览器」对Token合约部署、调用操作之后,在浏览器找不到自己的Token信息。于是产品经理第一时间拉着视觉、开发们,完成了测试网超脑浏览器的Token查询的设计,同时新版的Ultrain浏览器也在很多方面做了优化,继续往下看吧!

1、新增首页数据
打开新版Ultrain浏览器,首页除了全新的视觉设计,一眼就能看到块高、交易数、账户数、合约数、Token数的信息,帮助用户直观地了解超脑链最新数据。

2、Token查询
部署完Token合约,直接在超脑浏览器就可以查询到Token信息,超方便啦!

3、查看账户内Token信息
除了Token列表,在自己的账户内也可以查看账户拥有的Token信息啦。不用手动搜索,浏览器自动同步账户内Token信息,很贴心了哦~

4、无线端兼容
新版的整体视觉做了优化,包括列表页、详情页、创建账户流程、合约部署和调用流程等,同时也特别对无线端做了兼容处理,让用户在手机上操作时更舒服。

5、其他
开发还在性能上、缓存策略上进行了优化,使页面加载速度有了明显提升。

Ultrain浏览器的地址(https://explorer.ultrain.io/),你也来试一试吧!有问题的话,可以到开发者门户-论坛(https://bbs.ultrain.io/)给我们留言哦!

read more

consensus and smart contract development

Ultrain Technology Roadmap in 2020
B

The Ultrain main net has been running steadily for a year since it was launched on 2019.4.15. At present, the Ultrain network is composed of nearly 700 nodes, which are distributed in many countries and regions such as China, the East and West Coast of the United States, Australia, South Africa and Germany. The network deployment methods include public cloud networks (Alibaba Cloud, Amazon Cloud, Microsoft Cloud, Kingsoft Cloud), enterprise intranet, enterprise private network, open Internet and home broadband network.

On the basis of technical stability and shaping, Ultrain’s main task in 2020 is to realize the commercial implementation of blockchain technology. In the second half of 2019, we spent a lot of energy exploring and designing business models with our many business partners, and we have a full understanding of the advantages and disadvantages of blockchain technology in business competition:”Blockchain Business and Technology Status and Development Trend Outlook”. On this basis, we have determined the business model that we hope to be empowered by Ultrain technology in 2020: in a fully competitive industry, establish a mutual trust franchise business model at low cost.

In order to achieve this goal, Ultrain’s technology needs to be further upgraded from the following aspects in 2020:

Compliance with business compliance requirements: In recent months, various ministries and commissions have issued normative guidelines related to blockchain technology, such as the “Financial Distributed Ledger Technical Security Specification” issued by the Central Bank. These specifications will become the basic threshold for the application of enterprises in the future. In order to meet the requirements of these specifications and achieve commercial compliance, Ultrain needs to conduct further research and development in many aspects;

Consensus innovation: The franchise business model has two characteristics, one is that there are many franchisees, and the other is that the geographical distribution of franchisees is very scattered. This mainly brings a variety of technical challenges, including the different network environments of franchisees, and the need for users to automatically adapt to different networks without perception. There are many network nodes, and the online time of franchisees is not fixed. How to maintain the stability of the blockchain network in the face of a dynamic network. As an open network, how to ensure the security of the network; these aspects are the technical challenges we need to solve this year;

Blockchain privacy protection: In the business environment, privacy protection is the bottom line requirement for system operation. The “Personal Financial Information Protection Technical Specification” issued by the central bank at the beginning of this year can be used as a reference. Ultrain has a deep accumulation of blockchain privacy protection solutions. This year we will form a commercial solution to export and provide services;

The above are the three technical routes of Ultrain in 2020. We have further divided this technical route:

The above is the technology roadmap of Ultrain in 2020, which contains a number of world-leading technological breakthroughs. We will further publish the technical implementation details at each step and share our progress with you. Hope that Ultrain's breakthrough in technology can contribute to the commercial landing of blockchain technology.

read more

Industry dynamics and latest news about blockchain and currency

Ultrain Monthly Report(03/16–04/12)
B

Ultrain Monthly Report(03/16–04/12)

Following is the monthly report on the progress of the project from Mar. 16th -Apr. 12th, which contains two items: project development progress and community dynamic update. It is for the community members to check. Thank you for your attention.

Technology Update from Ultrain (3/16–4/12)
Ultrain’s Core Technology

According to the Central Bank’s “Financial Distributed Ledger Technical Security Specification” compliance check and improve the node code;

The node code adds national secret algorithm support to the transaction account;

Establish an on-chain data table to support miners’ daily reward data on-chain storage;

Optimize the historical data query code and improve the browser query response speed;

Calculate the Merkel tree hash of the world state change data to provide world state data verification.

Ultrain’s Ecosystem

A new version of the user relationship diagram, store settings and other functions are launched on the backstage of the merchant, which completes the development of funds management, product management, store opening help and other pages, and is scheduled to go online at the end of April;

The new version of the Hyper-physical APP is launched, optimizing the rich text display on the product detail page, optimizing the homepage effect and other functions;

Optimize the merchant entry process, complete function development such as shop reward activities and shop package purchase, and plan to go online after passing the test in early May.

Ultrain Developer Kit

U3 SDK adds national secret algorithm support;

Optimize the Ultrain One wallet wealth page to support reading on the miner reward data chain;

Optimize Ultrain One wallet transfer code to improve transfer response speed.

Ultrain’s Latest Community & Event Update

Ultrain overseas ambassadors synchronized the development of the blockchain industry around the world

In March, due to multiple factors, the global financial market was in crisis. But at the same time, in this special period, emerging technologies such as blockchain have also accelerated. Ultrain’s overseas ambassadors conducted a survey to provide you with an in-depth understanding of the development of the blockchain industry around the world.

Ultrain wished community members a happy April Fools’ Day!

Ultrain launched the technology roadmap of 2020

The Ultrain mainnet has been running steadily for a year since it was launched on 2019.4.15. On the basis of technical stability and shaping, Ultrain ’s main task in 2020 is to achieve the commercial implementation of blockchain technology, and it has clarified the business model that hopes to be empowered by Ultrain technology in 2020: in a fully competitive industry To establish a mutual trust franchise business model through low cost.

In order to achieve this goal, Ultrian’s technology needs to be further upgraded from the following aspects in 2020: 1. Compliance with business compliance requirements; 2. Consensus innovation; 3. Blockchain privacy protection. We have further divided the technical route.

The above is the progress report of Ultrain from Mar 16th to Apr 12th, looking forward to more exciting contents after that!

read more

hacker marathon and regular meetup or online game

Ultrain Monthly Report(5/11–6/7)
B

Following is the monthly report on the progress of the project from May. 11th -Jun.7th, which contains two items: project development progress and community dynamic update. It is for the community members to check. Thank you for your attention.

Technology Update from Ultrain (5/11–6/7)

Ultrain’s Core Technology

• Ultrain infrastructure

Complete the development of the Windows version of the family mining machine software, and implement the Windows 10 environment automation deployment tool to complete the internal test;

Node software adds on-chain data compression and encrypted storage, and increases data distributed storage mechanism support;

Improve the certificate system management tool to support encrypted authentication communication between nodes and between the client and the server.

Ultrain’s Ecosystem

New functions of exporting merchant orders, customizing reward rules, intelligent display of user data and other functions have been released on the S.I.R platform and updated versions have been released;

The S.I.R system completes the product video, custom sharing copy and other function development, and enters the test stage;

Complete the construction and development of the blockchain enterprise service platform and data upload, and complete the development of related systems such as new marketing activities for blockchain games.

Ultrain Developer Kit

Complete TypeScript refactoring for UltrainOne to improve code readability and maintainability.

Ultrain’s Latest Community & Event Update

Ultrain fully introduced its own blockchain certificate management system

Currently, the mainstream blockchain technology in China is called an open license chain. The license chain refers to the owners of all the nodes that make up the license chain. Their identities are authenticated, and they can only join the blockchain network after being authorized by the license. In this scenario, the network is open to authorized organizations or institutions, and there is a collaborative relationship between the participants on the chain, with an access mechanism. As a complete solution, the PKI/CA system can provide identity authentication certificates for each participant in the license chain to realize access control. It can be said that the certificate mechanism is the cornerstone of the permission chain network security.

Recently, Ultrain technical experts wrote an article, which describes the Ultrain certificate management system in detail after describing the basic concepts of PKI/CA as necessary.

Ultrain has completed development of many new functions

Ultrain independently developed a one-stop user growth technology service platform based on a small program store. The super-item system has completed iterations. It has a variety of powerful tool libraries to support the needs of merchant stores in multiple scenarios: SMS and subscription notifications, merchandise Fission posters, user relationship management … In the future, there will also be functions such as social dynamics and interaction, live broadcast playback, etc.

At present, Superphysical is engaged in store exploration and nugget activities, inviting merchants from all walks of life to open stores, and you will receive a reward for opening a store. Permanently receive 1% of the order transaction amount as a reward.

Ultrain is working closely with multiple business partners

Recently, Ultrain has helped a blockchain game to complete the construction of its marketing system, and has also completed the construction and development of a blockchain enterprise service center and data upload. In addition, there are many business partners in close negotiation and cooperation.

The above is the progress report of Ultrain from May 11th to Jun 7th, looking forward to more exciting contents after that!

read more

Dapp develop tools and high-quality application recommendations

How to build an end-to-end DApp on Ultrain - 2
R

Step2:Write DApp

There are two Dapps to be written, one is MiningDapp, the other is UDapp. We use the Javascript SDK U3.js to write the DApps. To be simple, we create the two DApps in one project.

Written by DApp

In WebStorm, create a new project -> Node.js Express App-> Template select Pug (Jade); modify the project name to CarbonDApp;

Click ‘Create’ to create a project

Import project dependent class library

Copy all the directories in node_modules in CarbonProject to the node_modules directory of CarbonDApp, and repeat the directory skipping without copying;
Copy the CarbonDApp/node_modules/u3.js/dist/u3.js file to the CarbonDApp/public/javascripts directory.

Modify the DApp server port

Since the default 3000 port is already occupied, you need to modify the server port of the DApp.

Open the bin/www file and find var port = normalizePort(process.env.PORT || '3000'); change 3000 to 3001

Create an account information browsing page

Create an index.html page in the public directory and add the following code to the page:

<html> <head> <meta charset="UTF-8"> <title>test</title> <link rel="stylesheet" href="/stylesheets/style.css"> <script src="./javascripts/u3.js"></script> <script> let u3 = U3.createU3({ httpEndpoint: 'http://127.0.0.1:8888', httpEndpoint_history: 'http://127.0.0.1:3000', broadcast: true, debug: false, sign: true, logger: { log: console.log, error: console.error, debug: console.log }, chainId:'2616bfbc21e11d60d10cb798f00893c2befba10e2338b7277bb3865d2e658f58', symbol: 'UGAS' }); async function getBalanceInfo() { let SYMBOL = 'CARB'; let account = 'ben'; const ben_balance = await u3.getCurrencyBalance({ code:'ben', symbol: SYMBOL, account: account }); document.getElementById("carbon_balance").innerHTML = '账户余额:'+ben_balance; const bob_balance = await u3.getCurrencyBalance({ code:'ben', symbol: SYMBOL, account: 'bob' }); document.getElementById("bob_balance").innerHTML = '账户余额:'+ bob_balance; const tom_balance = await u3.getCurrencyBalance({ code:'ben', symbol: SYMBOL, account: 'tom' }); document.getElementById("tom_balance").innerHTML = '账户余额:'+tom_balance; const tony_balance = await u3.getCurrencyBalance({ code:'ben', symbol: SYMBOL, account: 'tony' }); document.getElementById("tony_balance").innerHTML = '账户余额:'+tom_balance; const jerry_balance = await u3.getCurrencyBalance({ code:'ben', symbol: SYMBOL, account: 'jerry' }); document.getElementById("jerry_balance").innerHTML = '账户余额:'+tom_balance; const jack_balance = await u3.getCurrencyBalance({ code:'ben', symbol: SYMBOL, account: 'jack' }); document.getElementById("jack_balance").innerHTML = '账户余额:'+tom_balance; } getBalanceInfo(); //transfer(); </script> </head> <body> <div style="padding:8px;border:1px solid #96c2f1;background:#eff7ff"> <h1>CarbonCoin发行方</h1> <p>账户:ben</p> <p>描述:进行CarbonCoin发行的发行方,持有所有未分配的CarbonCoin</p> <p id="carbon_balance"></p> </div> <div style="padding:8px;border:1px solid #96c2f1;background:#eff7ff"> <h1>节能设备1</h1> <p>账户:bob</p> <p>描述:通过节能产生CarbonCoin的节能设备1</p> <p id="bob_balance"></p> </div> <div style="padding:8px;border:1px solid #96c2f1;background:#eff7ff"> <h1>节能设备2</h1> <p>账户:tom</p> <p>描述:通过节能产生CarbonCoin的节能设备2</p> <p id="tom_balance"></p> </div> <div style="padding:8px;border:1px solid #96c2f1;background:#eff7ff"> <h1>航空公司C</h1> <p>账户:tony</p> <p>描述:大型航空公司,化石能源使用大户</p> <p id="tony_balance"></p> </div> <div style="padding:8px;border:1px solid #96c2f1;background:#eff7ff"> <h1>汽车制造商D</h1> <p>账户:jerry</p> <p>描述:大型汽车制造商,化石能源使用大户</p> <p id="jerry_balance"></p> </div> <div style="padding:8px;border:1px solid #96c2f1;background:#eff7ff"> <h1>CarbonCoin销毁账户</h1> <p>账户:jack</p> <p>描述:用于CarbonCoin销毁的账户,持有所有销毁的CarbonCoin</p> <p id="jack_balance"></p> </div> </body> </html> Start the DApp service, test the page
In the npm interface, double click the start button

After the server is successfully started, visit http://127.0.0.1:3001/index.html and the following page appears:

It can be seen that the issuer ben account holds 10 million of all CARB Tokens issued; other accounts have not yet held CARB Token;

Create a mining.html page

Mining.html page, energy-saving device 1 and energy-saving device 2 send the calorie value generated in the first 30 seconds to the energy smart contract every 30 seconds, and redeem CarbonCoin;

Create a mining.html page in the public directory, enter the following code:

<html> <head> <meta charset="UTF-8"> <title>test</title> <link rel="stylesheet" href="/stylesheets/style.css"> <script src="./javascripts/u3.js"></script> <script> let u3_bob = U3.createU3({ httpEndpoint: 'http://127.0.0.1:8888', httpEndpoint_history: 'http://127.0.0.1:3000', broadcast: true, debug: false, sign: true, logger: { log: console.log, error: console.error, debug: console.log }, chainId:'2616bfbc21e11d60d10cb798f00893c2befba10e2338b7277bb3865d2e658f58', keyProvider: '5JoQtsKQuH8hC9MyvfJAqo6qmKLm8ePYNucs7tPu2YxG12trzBt',//bob's private_key symbol: 'CARB' }); let u3_tom = U3.createU3({ httpEndpoint: 'http://127.0.0.1:8888', httpEndpoint_history: 'http://127.0.0.1:3000', broadcast: true, debug: false, sign: true, logger: { log: console.log, error: console.error, debug: console.log }, chainId:'2616bfbc21e11d60d10cb798f00893c2befba10e2338b7277bb3865d2e658f58', keyProvider: '5KXYYEWSFRWfNVrMPaVcxiRTjD9PzHjBSzxhA9MeQKHPMxWP8kU',//tom's private_key symbol: 'CARB' }); function wait(ms = 0) { return new Promise(res => setTimeout(res, ms)); } function randomFrom(lowerValue,upperValue) { return Math.floor(Math.random() * (upperValue - lowerValue + 1) + lowerValue); } async function mining() { let owner_account = 'ben'; const tr_bob = await u3_bob.contract(owner_account); const tr_tom = await u3_tom.contract(owner_account); // let amount = U3.format.UDecimalPad(2000,4); let heat_bob = randomFrom(15000,20000); let heat_tom = randomFrom(15000,20000); await tr_bob.recordHeat(heat_bob,{ authorization: [`bob@active`] }); await tr_tom.recordHeat(heat_tom,{ authorization: [`tom@active`] }); var d=new Date(); var t=d.toLocaleTimeString(); document.getElementById("bob_log").innerHTML = 'time :'+t+', heat value :'+ heat_bob; document.getElementById("tom_log").innerHTML = 'time :'+t+', heat value :'+ heat_tom; } mining(); var int=self.setInterval("mining()",30*1000); </script> </head> <body> <div style="padding:8px;border:1px solid #96c2f1;background:#eff7ff"> <h1>节能设备1</h1> <p>账户:bob</p> <p>描述:通过节能产生CarbonCoin的节能设备1</p> <p id="bob_log"></p> </div> <div style="padding:8px;border:1px solid #96c2f1;background:#eff7ff"> <h1>节能设备2</h1> <p>账户:tom</p> <p>描述:通过节能产生CarbonCoin的节能设备2</p> <p id="tom_log"></p> </div> <div style="padding:8px;border:1px solid #96c2f1;background:#eff7ff"> <button onclick="int=window.clearInterval(int)">stop</button> </div> </body> </html>

Go to http://127.0.0.1:3001/mining.html and the following page appears:

There are two things to note here.

When sending data to the energy smart contract, you need to hold the private key of the account before you can sign and send it. In order to simplify the programming, the private key is directly written to the webpage. In the actual program, the private key needs to be protected and hidden.

To simplify the writing, the Bob and tom DApp programs are written directly to a page. Actually, they should be two DApp program instances, which are running on two devices respectively.

Now our energy-saving equipment can already send data to the smart contract, and after the energy smart contract receives the data, it will pass the data to the operator server, and the operator server will call the energy smart contract again to exchange carboncoin. So we need to establish EnergyServer;

Step3: EnergyServer

Establish event monitor and handle events

In this section, we will deal with the above calorific value data upload event.

1.1 Establish listener event server code

In the bin directory of the CarbonDApp project, create a new file msgBroker.js and enter the following code.

const { createU3 , format} = require('u3.js/src'); const http = require('http'); const port = 3002; let u3 = createU3({ httpEndpoint: 'http://127.0.0.1:8888', httpEndpoint_history: 'http://127.0.0.1:3000', broadcast: true, debug: false, sign: true, logger: { log: console.log, error: console.error, debug: console.log }, chainId:'2616bfbc21e11d60d10cb798f00893c2befba10e2338b7277bb3865d2e658f58', keyProvider:'5JbedY3jGfNK7HcLXcqGqSYrmX2n8wQWqZAuq6K7Gcf4Dj62UfL',//ben's private key symbol: 'UGAS' }); let server = http.createServer((request, response) => { const { headers, method, url } = request; console.log(method); console.log(url); let body = []; request.on('error', (err) => { console.error(err); }).on('data', (chunk) => { body.push(chunk); }).on('end', () => { body = Buffer.concat(body).toString(); console.log("received msg:", body); if (body != null && body.trim()!="") { var obj = JSON.parse(body); let heatValue = JSON.parse(obj[1]).heat.split(",")[0]; let account = JSON.parse(obj[1]).heat.split(",")[1]; exchangeCarbonCoin(account,heatValue); } response.on('error', (err) => { console.error(err); }); response.statusCode = 200; response.setHeader('Content-Type', 'application/json'); response.write("ok"); response.end(); }); }); server.keepAliveTimeout = 0; server.timeout = 0; server.listen(port, function () { console.log((new Date()) + " Server is listening on port " + port); }); function wait(ms = 0) { return new Promise(res => setTimeout(res, ms)); } async function exchangeCarbonCoin(account,heat) { let SYMBOL = 'CARB'; let code = 'ben'; const tr = await u3.contract(code); let heatValue = format.DecimalPad(heat,4); const result = await tr.exchangeCarbonCoin('ben', account, heatValue+' ' + SYMBOL, 'test', { authorization: [`ben@active`] }); let tx = await u3.getTxByTxId(result.transaction_id); while (!tx.irreversible) { await wait(1000); tx = await u3.getTxByTxId(result.transaction_id); if (tx.irreversible) { console.log(tx); break; } } }

The code establishes a service on port 3002. After the energy-saving device uploads its calorific value, the smart contract will send the energy-saving device to the service to upload the calorific value data. The service calls the exchangeCarbonCoin method of the energy smart contract to exchange the CarbonCoin.

1.2 Establish a listener event server startup script

Open the CarbonDApp/package.json file and add the following code to the scripts property: "event": "node ./bin/msgBroker"

1.3 Start the listening server

Refresh the npm window with the ‘event’ option

Double-click event to complete server startup

1.4 Register event monitoring mechanism on the chain

Query the internal network address of the machine through the ifconfig command, for example: 10.20.8.32

In the CarbonProject/test directory, create the registerEvent.js file; enter the following code in the file

const U3Utils = require('u3-utils/dist/es5'); const { createU3, format, listener } = require('u3.js/src'); const config = require('../config'); const chai = require('chai'); require('chai') .use(require('chai-as-promised')) .should(); const should = chai.should(); const expect = chai.expect; const assert = chai.assert; describe('Test cases', function() { it('event register', async () => { let account = 'ben'; const u3 = createU3(config); await u3.registerEvent(account, 'http:// 10.20.8.32:3002'); U3Utils.wait(1000); }); it('event unregister', async () => { let account = 'ben'; const u3 = createU3(config); await u3.unregisterEvent(account, ' http:// 10.20.8.32:3002'); U3Utils.wait(1000); }); });

Note that the registered address is modified to be the internal network address of the machine, and 127.0.0.1 cannot be used.
Run the event register test case to complete the event registration;

1.5 Test calorie value for CarbonCoin function

Visit http://127.0.0.1:3001/mining.html page, every 30 seconds, both bob and tom will randomly send a random value between 15000 and 20000 as the calorific value to convert the smart contract to CarbonCoin;
Visit and refresh the http://127.0.0.1:3001/index.html page, you can find that the CarbonCoin account of bob and tom is increasing every 30 seconds;

Step4:Improve DApp functionality

Add transfer function

After the energy-saving equipment acquires CarbonCoin, it can sell CarbonCoin to the enterprise, such as airlines, etc. The simple embodiment is that the equipment account can be transferred to the corporate company account;

Open the /CarbonDApp/index.html page and add the code

1.1 U3 object used when establishing the transfer

let u3_bob = U3.createU3({ keyProvider:'5JoQtsKQuH8hC9MyvfJAqo6qmKLm8ePYNucs7tPu2YxG12trzBt',//bob's private key }) let u3_tom = U3.createU3({ keyProvider:'5KXYYEWSFRWfNVrMPaVcxiRTjD9PzHjBSzxhA9MeQKHPMxWP8kU',//tom's private key })

1.2 Add the js code of the transfer to call the corresponding smart contract method

async function sendCoin(from,to){ let SYMBOL = 'CARB'; let code = 'ben'; let coins = U3.format.DecimalPad(this.randomFrom(100,500),4); if (from == 'bob'){ const tr = await u3_bob.contract(code); const result = await tr.transfer(from, to, coins + ' ' + SYMBOL, 'sendCoin', { authorization: [`bob@active`] }); let tx = await u3_bob.getTxByTxId(result.transaction_id); while (!tx.irreversible) { await wait(1000); tx = await u3_bob.getTxByTxId(result.transaction_id); if (tx.irreversible) { alert("bob send coin success:"+ coins); break; } } } else if (from == 'tom'){ const tr = await u3_tom.contract(code); const result = await tr.transfer(from, to, coins + ' ' + SYMBOL, 'sendCoin', { authorization: [`tom@active`] }); let tx = await u3_tom.getTxByTxId(result.transaction_id); while (!tx.irreversible) { await wait(1000); tx = await u3_tom.getTxByTxId(result.transaction_id); if (tx.irreversible) { alert("tom send coin success:"+ coins); break; } } } }

1.3 Add a call to the sendcoin() method on the page, update the following code

<div style="padding:8px;border:1px solid #96c2f1;background:#eff7ff"> <h1>节能设备1</h1> <p>账户:bob</p> <p>描述:通过节能产生CarbonCoin的节能设备1</p> <p id="bob_balance"></p> <p><a href="#" OnClick="sendCoin('bob','tony')">给航空公司C转账</a></p> </div> <div style="padding:8px;border:1px solid #96c2f1;background:#eff7ff"> <h1>节能设备2</h1> <p>账户:tom</p> <p>描述:通过节能产生CarbonCoin的节能设备2</p> <p id="tom_balance"></p> <p><a href="#" OnClick="sendCoin('tom','jerry')">给汽车制造商D转账</a></p> </div>

1.4 Access the page and test the function

Visit: http://127.0.0.1:3001/index.html, click the "Transfer to the airline C" button, wait for a period of time (up to about 10 seconds, confirm the time for the Ultrain transaction), the following prompt appears, indicating the transfer success.

Add a company to convert CarbonCoin to a charity point function

By converting CarbonCoin into charitable points, the company makes its own contribution to reducing carbon emissions and enhances its reputation:

Open the /CarbonDApp/index.html page and add the code

2.1 U3 object used when establishing point redemption

let u3_tony = U3.createU3({ keyProvider:'5KbHvFfDXovPvo2ACNd23yAE9kJF7Mxaws7srp6VapjMr7TrHZB',//tony's private key }) let u3_jerry = U3.createU3({ keyProvider:'5JFz7EbcsCNHrDLuf9VpHtnLdepL4CcAEXu7AtSUYfcoiszursr',//jerry's private key })

2.2 Add the redeemed js code to call the corresponding smart contract method

async function exchangeScore(account){ let SYMBOL = 'CARB'; let code = 'ben'; let to = 'jack'; let coins = U3.format.DecimalPad(this.randomFrom(10,50),4); if (account == 'tony'){ const tr = await u3_tony.contract(code); const result = await tr.exchangeScore(account, to, coins + ' ' + SYMBOL, 'sendCoin', { authorization: [`tony@active`] }); let tx = await u3_tony.getTxByTxId(result.transaction_id); while (!tx.irreversible) { await wait(1000); tx = await u3_tony.getTxByTxId(result.transaction_id); if (tx.irreversible) { alert("tony buy score success:"+ coins); break; } } } else if (account == 'jerry'){ const tr = await u3_jerry.contract(code); const result = await tr.exchangeScore(account, to, coins + ' ' + SYMBOL, 'sendCoin', { authorization: [`jerry@active`] }); let tx = await u3_jerry.getTxByTxId(result.transaction_id); while (!tx.irreversible) { await wait(1000); tx = await u3_jerry.getTxByTxId(result.transaction_id); if (tx.irreversible) { alert("jerry buy score success:"+ coins); break; } } } }

2.3 Add a call to the exchangeScore() method on the page, update the following code

<div style="padding:8px;border:1px solid #96c2f1;background:#eff7ff"> <h1>航空公司C</h1> <p>账户:tony</p> <p>描述:大型航空公司,化石能源使用大户</p> <p id="tony_balance"></p> <p><a href="#" OnClick="exchangeScore('tony');return false;">购买公益积分</a></p> </div> <div style="padding:8px;border:1px solid #96c2f1;background:#eff7ff"> <h1>汽车制造商D</h1> <p>账户:jerry</p> <p>描述:大型汽车制造商,化石能源使用大户</p> <p id="jerry_balance"></p> <p><a href="#" OnClick="exchangeScore('jerry');return false;">购买公益积分</a></p> </div>

2.4 Access the page and test the function

Visit: http://127.0.0.1:3001/index.html, click the "Buy Charity Points" button, wait for a period of time (up to about 10 seconds, confirm the time for the Ultrain transaction), the following prompt appears, indicating that the points are successfully redeemed. At the same time, you can see the number of CarbonCoins destroyed in the CarbonCoin destruction account at the bottom of the page.

Query the public welfare points exchange history

By enquiring the redemption history of charity points, we can establish a ranking of corporate charity points.

3.1 Creating a page

In the CarbonDApp/public/ directory, create a new leaderboard.html and enter the following code:

<html> <head> <meta charset="UTF-8"> <title>leaderboard</title> <link rel="stylesheet" href="/stylesheets/style.css"> <script src="./javascripts/u3.js"></script> <script> let u3 = U3.createU3({ httpEndpoint: 'http://127.0.0.1:8888', httpEndpoint_history: 'http://127.0.0.1:3000', broadcast: true, debug: false, sign: true, logger: { log: console.log, error: console.error, debug: console.log }, chainId:'2616bfbc21e11d60d10cb798f00893c2befba10e2338b7277bb3865d2e658f58', symbol: 'UGAS' }); function wait(ms = 0) { return new Promise(res => setTimeout(res, ms)); } async function getLeaderboard() { let owner_account = 'ben'; const tr = await u3.contract(owner_account); const result = await u3.getAllTxs(1,10000000,{"actions.name":"exchangeScore"},{_id:-1}); //console.log(result); let content = ''; for ( let i = 0 ;i< result.results.length;i++){ content = content + '<tr><td>'+ result.results[i].actions[0].data.from+":"+result.results[i].actions[0].data.quantity +'</td></tr>'; } document.getElementById("leaderboard").innerHTML = content; } getLeaderboard(); </script> </head> <body> <div style="padding:8px;border:1px solid #96c2f1;background:#eff7ff"> <h1>leaderboard</h1> <table id="leaderboard"> </table> </div> </body> </html>

We use the u3.getAllTxs(1,10000000,{"actions.name":"exchangeScore"},{_id:-1}); method to query all redemption transactions and print their specific data to the page.

3.2 Run page

Visit http://127.0.0.1:3001/leaderboard.html and you can see the following page:

Here is a history of all points redemption.

Summary

This tutorial system describes how to write an end-to-end web version of the DApp application. Although it has been simplified in the process of writing, it generally describes the overall picture of DApp application development, developers can do the basis of this framework. Enrich and improve your DApp application.

About developing DApp on iOS and Android, you can integrate u3.js into the corresponding hybrid Native development framework, and the principle is the same as the web version DApp.

read more