Translate

Sunday, April 25, 2021

Blockchain Implementation With Java Code

 Source: Blockchain Implementation With Java Code - DZone Java

Let's take a look at a possible blockchain implementation using Java. We build up from first principles and develop some code to help show how it all fits together.

 · Java Zone · Tutorial

Bitcoin is hot — and what an understatement that is. While the future of cryptocurrency is somewhat uncertain, blockchain — the technology used to drive Bitcoin — is also very popular.

Blockchain has an almost endless application scope. It also arguably has the potential to disrupt enterprise automation. There is a lot of information available covering what and how blockchain works. We have a free whitepaper that goes into blockchain technology (no registration required).

This article will focus on the blockchain architecture; particularly, demonstrating how the "immutable, append-only" distributed ledger works with simplistic code examples.

As developers, seeing things in code can be much more useful in understanding how it works when compared to simply reading technical articles. At least that's the case for me. So, let's get started!

Blockchain in a Nutshell

Let's first give a quick summary of blockchain. A block contains some header information and a set or block of transactions of any type of data. The chain starts with a first (Genesis) block. As transactions are added/appended, new blocks are created based on how many transactions can be stored within a block.

When a block threshold size is exceeded, then a new block of transactions is created. The new block is linked to the previous block, hence the term blockchain.

Immutability

Blockchains are immutable because an SHA-256 hash is computed for transactions. A block's contents are also hashed which provide a unique identifier. Moreover, the hash from the linked, previous block is also stored and hashed in the block header.

This is why trying to tamper with a blockchain block is basically impossible, at least with current computing power. Here's a partial Java class definition showing the properties of the block.

Notice the injected generic type is of type Tx. This allows transaction data to vary. Also, the previousHash property will reference the previous block's hash. The merkleRoot and nonce properties will be described in a bit.

Block Hash

Each block can compute a block hash. This is essentially a hash of all the block's properties concatenated together, including the previous block's hash and a SHA-256 hash computed from that.

Here is the method defined in the Block.java class that computes the hash.

The block transactions are serialized to a JSON string so it can be appended to the block properties before hashing.

The Chain

The blockchain manages blocks by accepting transactions. When a predetermined threshold has been reached, then a block is created. Here is a SimpleBlockChain.java partial implementation:

Notice that the chain property holds a list of Blocks typed with a Tx type. Also, the no arg constructor creates an initial "genesis" block when the chain is created. Here is the source for the newBlock() method.

This new block method will create a new block instance, seed appropriate values, and assign the previous block's hash (which will be the hash of the head of the chain). It will then return the block.

Blocks can be validated before being added to the chain by comparing the new block's previous hash to the last block (head) of the chain to make sure they match. Here's a SimpleBlockchain.java method depicting this.

The entire blockchain is validated by the looping-over of the chain to ensure a block's hash still matches the previous block's hash.

Here is the SimpleBlockChain.java validate() method implementation.

You can see that trying to fudge transaction data or any other property in any way is very difficult. And, as the chain grows, it continues to get very, very, very difficult, essentially impossible — that is, until quantum computers are available!

Adding Transactions

Another significant technical point of blockchain technology is that it is distributed. The fact that they are append-only helps in duplicating the blockchain across nodes participating in the blockchain network. Nodes typically communicate in a peer-to-peer fashion, as is the case with Bitcoin, but it does not have to be this way. Other blockchain implementations use a decentralized approach, like using APIs via HTTP. However, that is a topic for another article.

Transactions can represent just about anything. A transaction could contain code to execute (i.e Smart Contract) or store and append information about some kind of business transaction.

Smart contract: Computer protocol intended to digitally facilitate, verify, or enforce the negotiation or performance of a contract.

In the case of Bitcoin, a transaction contains an amount from an owner's account and amount(s) to other accounts (e.g. transferring Bitcoin amounts between accounts). The transaction also includes public keys and account IDs within it, so transferring is done securely. But that's Bitcoin-specific.

Transactions are added to a network and pooled; they are not in a block or the chain itself.

This is where a blockchain consensus mechanism comes into play. There are a number of proven consensus algorithm and patterns beyond the scope of this article.

Mining is a consensus mechanism that Bitcoin blockchains use. That is the type of consensus discussed further down this article. The consensus mechanism gathers transactions, builds a block with them, and then adds the block to the chain. The chain then validates the new block of transactions before adding to the chain.

Merkle Trees

Transactions are hashed and added to the block. A Merkle Tree data structure is created to compute a Merkle Root hash. Each block will store the root of the Merkle tree, which is a balanced binary tree of hashes where interior nodes are hashes of the two child hashes, all the way up to the root hash, which is the Merkle Root.

This tree is used to validate the block transactions. If a single bit of information is changed in any transaction, the Merkle Root will be invalid. Also, they can help with transmitting blocks in a distributed fashion, since the structure allows only a single branch of transaction hashes required to add and validate the entire block of transactions.

Here's the method in the Block.java class that creates a Merkle Tree out of the transaction list.

This method is used to compute a Merkle Tree root for the block. The companion project has a Merkle Tree unit test that attempts to add a transaction to a block and verify that the Merkle Roots have changed. Here is the source code for the unit test.

This unit test emulates validating transactions, then changing a transaction in a block outside of the consensus mechanism, e.g. if someone tries to change transaction data.

Remember, blockchains are append-only, and as the blockchain data structure is shared between nodes, block data structure (including the Merkle Root) are hashed and connected to other blocks. All nodes can validate new blocks and existing blocks can be easily proved as valid. So, a miner trying to add a bogus block or a node attempting to adjust older transactions are effectively not possible before the sun grows to a supernova and gives all a really nice tan.

Mining Proof of Work

The process of combining transactions in into a block, then submitting it for validation by members of the chain, is referred to as "mining" in the Bitcoin world.

More generally, in blockchain speak, this is called consensus. There are different types of proven distributed consensus algorithms. Which mechanism to use is based upon whether you have a public or permissioned blockchain. Our white paper describes this more in depth, but this article is focusing on the blockchain mechanics, so this example we will apply a proof-of-work consensus mechanism.

So, mining nodes will listen for transactions being executed by the blockchain and will perform a simple mathematical puzzle. This puzzle produces block hash with a predetermined set of leading zeros using a nonce value that is changed on every iteration until the leading zero hash is found.

The example Java project has a Miner.java class with a proofOfWork(Block block) method implementation, as shown below.

Again, this is simplified, but the miner implementation will perform a proof-of-work hash for the block once a certain number of transactions have been received. The algorithm simply loops and creates an SHA-256 hash of the block until the leading number hash is produced.

This can take a lot of time, which is why specific GPU microprocessors have been implemented to perform and solve this problem as fast as possible.

Unit Tests

You can see all these concepts pulled together with the Java example project's JUnit tests available on GitHub.

Give this a run. It will let you check out how this simple blockchain works.

Also, if you are a C#'er reading, this (we won't tell anyone), we also have these same examples written in C#. Here is the link to the example C# blockchain implementation.

Final Thoughts

Hopefully, this post has provided you enough interest and insight to keep researching blockchain technology.

All of the examples introduced in this article are used in our in-depth blockchain white paper (no registration required to read). These same examples are in more detail in the white paper.

Also, if you want to see a full blockchain implementation in Java, here's a link to the open-source BitcoinJ project. You'll see these concepts in action in a real production implementation.

If so, next recommended learning steps are to check out a more production-based open-source blockchain framework. A good example is HyperLedger Fabric. That will be the subject of my next article — stay tuned!

Friday, April 2, 2021

Angular vs. React vs. Vue: Which Framework is Best in 2021?

 Source: https://dzone.com/articles/angular-vs-react-vs-vue-which-framework-is-best-to

One is a UI library (React), another is a seasoned front-end framework (Angular), and the youngest among them (Vue) may be termed as a progressive framework.

  · Web Dev Zone · Analysis

You may be a React developer, a Vue developer, or an Angular developer specializing only in these technologies. Still, you cannot ignore the constant comparison that the development community keeps making. And for good reason. One is a UI library (React), another is a seasoned full-fledged front-end framework (Angular), and the youngest among them (Vue) may be termed as a progressive framework. Each of these possesses some unique benefits and performance metrics that compel people to analyze the three.

Each of these frameworks is component-based and facilitates the rapid creation of UI features. They can be used interchangeably, well, almost for building front-end applications. However, they are not 100% the same.

This is why we decided to create a short guide for you but, most importantly, a structure for you to help decide on technologies in the future as well.

Let’s dig in.

License

As obvious as it may sound, make sure to thoroughly check its license before using an open-source framework or library. Luckily, React, Angular, and Vue all use the MIT license, which is bliss because it provides limited restrictions on reuse, even in proprietary software. However, always go the extra mile and understand the implications of the license before using any framework or software.

Architecture

Angular

Angular framework belongs to the MEAN stack, which is today the hottest technology stack for startups. Angular is a complete framework for web application development based on TypeScript and is mainly used for building single-page web applications (SPAs).

Unlike AngularJS — the original framework, Angular 2 doesn’t have a strict association with MV*-patterns because it is component-based. The way Angular is structured, there are Modules, Components, and Services.

In the Angular framework, each component has a Class or a Template that defines the application logic and MetaData (Decorators). This metadata of the component provides guidance about where the building blocks needed to create and present its view are.

Another important factor in the Angular architecture is that the templates are written in HTML. They may also include Angular template syntax with special directives to output reactive data and may render multiple elements.

Services — a distinct element of Angular applications — are used by Components for delegating business-logic tasks such as fetching data or validating input. While using Services is not strictly enforced, it is always wiser to structure apps as a set of disparate services that are reusable.

React

React is an open-source, front-end library primarily used for developing user interfaces. This flexible front-end solution doesn’t enforce a specific project structure. A React developer may start using it with just a few lines of code.

React is based on JavaScript, but for the most part, it is combined with JSX (JavaScript XML), which is a syntax extension that allows a developer to create elements containing HTML and JavaScript at the same time. Effectively, anything that a developer can create with JSX can also be created with the React JavaScript API. React Elements are more powerful than DOM elements and are the smallest building blocks of React apps.

React components are building blocks that determine independent and reusable pieces to be used throughout the web application.

Vue

Used for developing user interfaces and SPAs, Vue is an open-source Model-View-View-Model front-end JS library. Called a progressive framework, it is used with other tools for front-end development. Vue’s popularity is owing to its versatility, high performance, and its optimal user experience on a web application.

With Vue, a developer mostly works on the ViewModel layer to make sure that the application data is processed in a manner that allows the framework to render an up-to-date view.

Vue’s templating syntax combines recognizable HTML with special directives and features. The syntax lets a developer create View components.

Now Components in Vue are reusable, self-contained, and small. The SFCs or Single File Components with the extension .vue have HTML, JavaScript, and CSS so that all the relevant codes stay in one file.

In larger Vue.js projects, SFCs are usually recommended to organize code. To transpile SFCs into working JavaScript code, you need tools like Webpack or Browserify.

Purpose and Scope

Angular

Angular is best suitable for large-scale and advanced projects. These may include but not be limited to: 

  • Developing Progressive Web App (PWA).
  • Redesigning of a website application.
  • Building dynamic content-based web designs.
  • Creating large enterprise application that needs complex infrastructure.

React

React comes from the family of the MERN stack — a technology stack known for building sophisticated business applications. React becomes a powerful tool when used along with Redux or MobX, or any flux patterned library. React is best suited for the following projects:

  • For applications that involve many components with navigation items, collapsed/expanded accordion sections, active/inactive states, dynamic inputs, active/inactive buttons, user login, user access permissions, etc.
  • For projects that have scope for scale and growth because React components have declarative nature that makes way for easy handling around such complex structures.
  • When UI is the center of the web app.

Vue

Vue is best suited for solving short-term problems because Vue has an affordable and quick learning curve. It can integrate with existing code blocks easily.  Vue may be required when:

  • You need development projects of web apps with animations or interactive elements.
  • Prototyping without the need for advanced skills.
  • Applications requiring seamless integration with multiple other apps.
  • Faster launch of MVP.

Performance and Development

Angular

Some highlights in Angular’s performance are:

  • Has seamless third-party integrations for enhancing the functionality of the product/application.
  • Provides a robust collection of components leading to simplified art of writing, altering, and using the code.
  • Its 'ahead-of-time-compiler' bestows faster load times and security strength.
  • The MVC model helps in curtailing queries in the background by allowing separation of views.
  • Facilitates the use of dependency injection as external elements for decoupling components that make way for reusability and ease of management and testing.
  • Reduces the initial load time of a webpage by splitting the tasks into logical chunks.
  • Fully customizable designs.
  • Facilitates the compiling of HTML and TypeScript into JavaScript — leading to the faster compilation of the code much before the browser starts to load the web app.

React

React is comparable to Vue when it comes to performance because both have the same architecture, i.e., interaction with DOM. The performance of React web development can be assessed as follows: 

  • Supports bundling and tree-shaking — a feature crucial for reducing the end users’ resource loads.
  • Offers better control over the project due to one-way data-binding support.
  • It can be easily tested and monitored.
  • Best for complex applications that require frequent changes.

Vue

Incredibly fast is the phrase that’s most attached with Vue. Some of its performance metrics are:

  • Faster learning curve.
  • Efficient and sophisticated single-page application.
  • Versatility due to high-end features.

Benefits of Angular, React, Vue

Angular

Well-documented understanding of templates, forms, bootstrapping or details about architecture, components, and interaction between components:

  • Smooth two-way data binding.
  • MVC architecture.
  • Built-in module system.
  • Significant reduction of the initial load time of a webpage.

Popular applications built using Angular:

Youtube TV | PayPal | Gmail | Forbes | Google Cloud

React

  • Flexible code due to its modular structure. Saves time and cost.
  • Facilitates high performance of complex apps.
  • Easier to maintain code during React front-end development.
  • Supports mobile native applications for both Android and iOS platforms.

Popular applications built with React:

Tesla | AirBnB | CNN | Nike | Udemy | Linked-in

Vue

  • Small size facilitates easy installation and download. 
  • When properly harnessed, Vue can be reused.
  • Vue.js allows updating of elements in a web page without rendering the whole DOM since it is virtual. 
  • Requires less optimization.
  • Stimulates web application development and allows the experts to separate template-to-virtual DOM from the compiler.
  • Proven compatibility and flexibility.
  • The codebase remains light regardless of the scaling of the application.

Popular applications built with Vue:

Gitlab | Spendesk | Behance | 9Gag | Wizzair | Nintendo

Community Support and Learning Curve

React JS library is created by Facebook that enjoys a large community of coders and developers offering solutions to the biggest problems. Angular has a large community of developers who have answers to the most challenging and weirdest cases. Vue has a decent ecosystem and enjoys all the right characteristics of React library and Angular framework. When it comes to the learning curve, React is the quickest to learn and adapt, followed by Vue and Angular. 

Final Thoughts

From the point of view of front-end development, React will be the quickest to learn in 2021. Both Vue and React are lightweight, intuitive, and perform flawlessly.

Thursday, March 25, 2021

An Overview: How-to Implement Google's Structured Data

 Source: https://dzone.com/articles/how-to-implement-google-structured-data 

by Rob Hinds    · Feb 27, 21 · Web Dev Zone · Tutorial

Google's Structured Data Schema helps you be a better web citizen as well as bringing SEO benefits, and if you have a dynamic web app, should be easy to implement.


As a result of working in web products (both personal and professional), I have become quite au fait with SEO from a technical point of view, and the purely technical things you can do to put you in good standing - all of which really, are just web best practices to be a good web citizen - things that we should be doing to make the web better (proper use of HTTP headers, mobile friendly designs, good performance for people on slower connections, etc.). 

One thing that is a bit above and beyond that is the use of Google's Structured Data. I will talk about what it is and what it does below, but if you are dynamically loading webpages (e.g. your website isn't just HTML on a web server, but either served from a server-side application, or is an API driven JS application), then you are most likely well placed to easily and immediately start implementing it.

1. What Is Structured Data?

Google has defined a set of schemas regarding Structured Data on websites. This is a schema that allows better definition of key data points from a given website. It's a sensible move by Google and is a natural progression for their search engine.

Think about it, there are millions of websites out there made up with sprawling HTML code and content - whilst HTML is a standard (more or less!) across the web, there are probably millions of different ways people use it. It would be nice if everyone used the H1 etc heading tags consistently, or if everyone used the <em> tag the same way (emphasis vs italics), but the reality is they don't - some sites will be using HTML as intended but many many more undoubtedly just rely on <span> or <div> tags combined with CSS classes to re-define every element they might need. 

This is all fine, Google is smart enough to pull out the content for indexing - yes, if you use span elements with custom styling for headings on your website rather than the H1+ tags then Google will penalise you, but it won't stop Google reading and indexing the site. What's more, its getting smarter all the time -  I'd probably back Google to be able to pull out relevant clips or question/answers directly in a fairly reliable way. However, they are Google and much like the Microsoft/IE of the 90s, they have the dominant market share so they can define their own standards for the web if they want to. That's exactly what Structured Data is. 

It's Google saying:

Hey, if you provide some data in your code that looks like this and is cool with our schema, then we will read that, so we don't have to guess or work out stuff. Or we can just keep trying to work it out from your HTML content.. it's your call

As mentioned earlier, if you have control over the source code and the data on your website, then this is really powerful. You can define specific (keyword heavy) snippets of content and explicitly tell Google about them - what's more the Schema for Structured Data lets you define content such as FAQ or how-to directions - so you can go beyond keyword heavy snippets and actually create FAQ for questions that you have identified from Google search trends (or whatever SEO tools you might use).  

Hopefully you get the picture by now - this is a pretty powerful tool.

2. Schema Tags: FAQ and HowTo

Two specific parts of the Structured Data Schema stood out to me as quite universally useful for websites, and also produce decent tangible results: FAQ schema and HowTo schema.

  • FAQ schema allows high level Q&A points to be provided in the metadata for Google - generally useful as most sites will have some element of their pages that could be presented as FAQ
  • HowTo schema allows step-by-step how to guides - less widely applicable, but if you have any website that provides how-to guides or anything with instructions this is applicable.

What exactly to these tags do and why do we care? Well, as well as trying to win favour with the all-seeing google search bot, if it gets picked up it also means we get more search real estate and increased accessibility to our content which should also increase the chance of click through conversion.

If you have ever seen search results like this:

Google search results

These points are being scraped from the site by Google from their schema tags - if you can automate the creation and inclusion of these for your site then you can be in a pretty good position to improve your SEO (still relatively low number of sites implementing these schemas).

3. Automating Your Schema Tags

As I have mentioned a couple of times, and as you have hopefully realised - if you have a dynamic website, you are likely already taking structured data (from your database for example, so reliably structured!) and building HTML pages (either server-side, or data as JSON to a JavaScript app for page creation client side) - but either way, we are starting off with structured data, and the Google Structured Data wants.. you got it, Structured Data! So if you have the content, it really is a generic, simple transform between structured data formats.

Below is some example code - It is based on Jekyll, as that's what my most recent personal project has been, but it's also pretty close to pseudocode, so hopefully you can easily translate it to whatever tech you use:

HTML

1
  {% if page.faqSchema %} 
2
    <script type="application/ld+json">
3
    {
4
      "@context": "https://schema.org",
5
      "@type": "FAQPage",
6
      "mainEntity": [
7
        {% for faq in page.faqSchema %}
8
          {
9
            "@type": "Question",
10
            "name": "{{faq.title}}",
11
            "acceptedAnswer": {
12
              "@type": "Answer",
13
              "text": "{{faq.answer}}"
14
            }
15
          }
16
          {% if forloop.last == false %}
17
            ,
18
          {% endif %}
19
        {% endfor %}
20
      ]
21
    }
22
  </script>
23
{% endif %}



As you can see, its a simple JSON based data structure and you just fill in the relevant parts of the object with your data. 

You can see the full code in my Jekyll food website over on GitHub here - likewise, you can see the end result in action on the website (hosted by GitHub pages, of course) too - the project was a food-science site - covering science and recipes, so a perfect match for FAQ (science pages) and HowTo (recipe pages). For example if you go to a recipe page view the page source, you will see the JSON schema at the top of the page, using the HowTo schema elements laying out resources required and then the steps required, if you compare that data with the actual page you will see the data mirrors each other (this is an important part, Google doesn't like what it thinks looks like "tricks"). Likewise on the Science of humidity in cooking in the page source you will see the JSON schema with FAQ:

JSON schema

4. Conclusion

If you have control of the data being loaded on to the page (a custom site - something like WordPress or another off the shelf platform might make this harder, but at the same time there are undoubtedly lots of plugins that already handle this for you on your given platform which make it even easier!), and are even vaguely interested in increasing organic traffic and search ranking, then I'd recommend implementing this. It's very easy to add (it's also primarily behind the scenes tech - it doesn't impact the visuals or design of the pages its added to) and can only be beneficial.

As with anything trying to improve SEO, its always hard to measure and get concrete details on, but its relatively low cost to add, minimal ongoing maintenance so I think its worth a shot.

If you have had experiences with Google's Structured data, good or bad, then I'd love to hear about it!