Monday, March 9, 2020

Are Cryptocurrency Micropayments The Future Of Content Marketing?

Clickbait, fake news, yellow journalism – media today is in a poor state.
Audiences are sick of sub-par content getting jammed down their throats, but they’re not always willing to pay for good content. It’s always going to be easier for clickbait to go viral and generate revenue based on traditional ad models. Other funding models, such as subscriptions and paywalls, have been implemented to mixed success – after all, on the Internet, there’s always the option of free, ad-supported content. Readers also like to consume their content from a range of sources and don’t want to be tied down to a single publisher.
So we need a new way of thinking when it comes to finding good content. Could the future of content lie in cryptocurrency micropayments?

Are Cryptocurrency Micropayments The Future Of Content Marketing?

What Are Micropayments?

Micropayments offer an alternative option that has the potential to support high-quality content without locking users into a single, long-term subscription. The concept behind micropayments is that you spend a small amount each time you view content.
Paying per article incentivizes publishers to produce high-quality content that satisfies the audience–if the audience constantly feels ripped off by a content source, they will stop making purchases. Because we do not pay for ad-supported content, we have no recourse if we feel like clickbait has wasted our time.

What’s Holding Micropayments Back?

Bitcoin and many other cryptocurrencies are prone to scaling problems. Billions of minuscule transactions would take up a lot of computing power and incur significant fees. If you are only sending a few cents for an article and a significant proportion gets eaten up in fees, it becomes an ineffective way of funding content.
To get around the inefficiencies and expense of writing small transactions to the blockchain, several organizations are using channels. Rather than recording every single transaction to the blockchain and incurring fees for each one, channel payments are recorded as a collection. The best way to think of it is like keeping a tab at the bar with your credit card. Rather than charging you for each drink, the bartender takes note of everything you order and only charges you at the end.
When a micropayment channel is created, a certain amount of bitcoin is locked into it and each individual payment is signed by the sender. The receiver can either withdraw each individual signed amount or wait until the channel is closed and withdraw the total. If the receiver waits until the channel is closed and only records this amount to the blockchain, it minimizes the number of transactions, making it more efficient and cheaper.

Coinetize

This startup is one of many that are looking to change the economic model for content creation. Coinetize bills itself as an online paywall and resource management system. It allows websites to use their service as a filter that only lets users access content if they pay a fee. Users buy Coinetize Creditswith either Bitcoins or their credit card. When they visit websites that use Coinetize, the user pays for restricted content with their pre-purchased credits.
Coinetize is easy for websites to set up. There are several different linking methods; DNS, reverse proxy, page directs and secret folders. These can be set up for free in minutes, without any credit or ID checks. The service charges customers a 1.8% fee, but they also offer 24-hour email support.

Brave

The Brave web browser has already achieved renown for bringing lighter ads and faster use to browsing. As part of their service, they now offer Brave Payment, which gives users a way to privately pay their favorite websites. Users can link their external Bitcoin wallet or their credit card to a wallet within the Brave system. If they want to use Brave Payments, they must fund a minimum of $5 each month.
Each month, the contributions are split among the sites that Brave users visit, based on the number of times visited, as well as the amount of time spent on each site. According to Brave’s founder, Brendan Eich, users can “reward the sites whose content they value and wish to support,” all without being tracked.

Can Micropayments Bring Back High-Quality Content?

Just like with Uber and Airbnb, you can make a side-hustle with your content. Imagine for a second, that every single blogpost, video and or podcast you publish your fans globally from their phone can send 25 cents, 50 cents or even a dollar for each piece of content. It seems small but it adds up! And above all, it puts the power back into you and your fans. Say, goodbye to depending on ads for revenue.
Although the rise of the internet may have coincided with the decline in content quality, things might not stay this way forever. Peer-to-peer micropayments are an emerging model of funding that show the potential for success.
Coinetize and Brave are just examples. The Dutch app, Blendle, has already demonstrated that some consumers are willing to spend money on the content that they want. Patreon, a platform that allows patrons to donate a set amount of money every time a piece of content is published, has funded over 50 million dollars to its creators.
Micropayments may never topple free content, but hopefully, they can provide a niche market for consumers who want excellent quality without the ads.

Continue Reading
No comments
Share:

What is Bitcoin Mining? An Easy Guide That Anyone Can Understand

Bitcoin may be the next big thing in finance, but it can be difficult for most people to understand how it works. There is a whole lot of maths and numbers involved, things which normally make a lot of people run in fear. What is Bitcoin mining? Well, it’s one of the most complex parts of Bitcoin, but it is also the most critical to its success.

As you know, Bitcoin is a  digital currency. Currencies need checks and balances, validation and verification. Normally central governments and banks are the ones who perform these tasks, making their currencies difficult to forge while also keeping track of them.
The big difference with Bitcoin is that it is decentralized. If there is no central government regulating it, then how do we know that the transactions are accurate?
How do we know that person A has sent 1 bitcoin to person B?
How do we stop person A from also sending that bitcoin to person C?
The answer is mining.

What is Bitcoin Mining? In Some Ways, Bitcoin Is Like Gold:

One of the most common analogies that people use for Bitcoin is that it’s like mining gold. Just like the precious metal, there is only a limited amount (there will only ever be 21 million bitcoin) and the more that you take out, the more difficult and resource-intensive it is to find. Apart from that, Bitcoin actually works quite differently and it’s actually quite genius once you can get your head around it. One of the major differences is that mining doesn’t necessarily create the bitcoin. Bitcoin is given to miners as a reward for validating the previous transactions. So how do they do it?
Bitcoin mining requires a computer and a special program. Miners will use this program and a lot of computer resources to compete with other miners in solving complicated mathematical problems. About every ten minutes, they will try to solve a block that has the latest transaction data in it, using cryptographic hash functions.

What are Hash Functions?

A cryptographic hash function is essentially one-way encryption without a key. It takes an input and returns a seemingly random, but fixed-length hash value.
For example, if you use Movable Type’s SHA-256 Cryptographic Hash Algorithm:
Message: How does mining work?
Hash Value: 46550fef 26f87ddd 5e15407f 45a0b8d2 9513291c 4e0f0acc 24a974de 907a1569
If you change even one letter of the original input, completely different hash value will be returned. This randomness makes it impossible to predict what the output will be.

How Are Hash Functions Useful For Bitcoin?

Because it is practically impossible to predict the outcome of input, hash functions can be used for proof of work and validation. Bitcoin miners will compete to find an input that gives a specific hash value (a number with multiple zeros at the start). The difficulty of these puzzles is measurable. However, they cannot be cheated on. This is because there is no way to perform better than by guessing blindly.
The aim of mining is to use your computer to guess until it comes up with a hash value that is less than whatever the target may be. If you are the first to do this, then you have mined the block (normally this takes millions and billions of computer-generated guesses from around the world). Whoever wins the block will get a reward of 12.5 bitcoins (as long as it becomes part of the longest blockchain). The winner doesn’t technically make the bitcoin, but the coding of the blockchain algorithm is set up to reward the person for doing the mining and thus helping to verify the blockchain. 
Each block is created in sequence, including the hash of the previous block. Because each block contains the hash of a prior block, it proves that it came afterward. Sometimes, two competing blocks are formed by different miners. They may contain different transactions of bitcoin spent in different places. The block with the largest total proof of work embedded within it is chosen for the blockchain.
This works to validate transactions because it makes it incredibly difficult for someone to create an alternative block or chain of blocks. They would have to convince everyone on the network that theirs is the correct one, the one that contains sufficient proof of work. Because everyone else is also working on the ‘true’ chain, it would take a tremendous amount of CPU power to beat them. One of the biggest fears of Bitcoin is that one group may gain 51% control of the blockchain and then be able to influence it to their advantage, although thankfully this has been prevented so far.

Who Are Bitcoin Miners?

Initially, bitcoin miners were just cryptography enthusiasts. People who were interested in the project and used their spare computer power to validate the blockchain so that they could be rewarded with bitcoin. As the value of bitcoin has gone up, more people have seen mining as a potential business, investing in warehouses and hardware to mine as many bitcoin as possible. 
These warehouses are generally set up in areas with low electricity prices, to further reduce their costs. With these economies of scale, it has made it more difficult for hobbyists to profit from Bitcoin mining, although there are still many who do it for fun.

Continue Reading
No comments
Share:

What is Hashing & Digital Signature in The Blockchain?

Hi, everyone. Today, we’re going to be talking about the word blockchain and breaking it down to understand what does it mean when someone says, “Blockchain.” We’re going to take the time to understand the cryptography behind the blockchain technology. There are two main cryptographic concepts that underpin blockchain technology. The first is hashing, and the second is digital signatures.

What is Hashing & Digital Signature in The Blockchain?

Hashing refers to the concept of taking an arbitrary amount of input data, applying some algorithm to it, and generating a fixed-size output data called the hash. The input can be any number of bits that could represent a single character, an MP3 file, an entire novel, a spreadsheet of your banking history, or even the entire Internet. The point is that the input can be infinitely big. The hashing algorithm can be chosen depending on your needs and there are many publicly available hashing algorithms. The point is that the algorithm takes the infinite input of bits, applies some calculations to them, and outputs a finite number of bits. For example, 256 bits.
What can this hash be used for? Common usage for hashes today is to fingerprint files, also known as check zones. This means that a hash is used to verify that a file has not been tampered with or modified in any way not intended by the author. If WikiLeaks, for example, publishes a set of files along with their MD5 hashes, whoever downloads those files can verify that they are actually from WikiLeaks by calculating the MD5 hash of the downloaded files, and if the hash doesn’t match what was published by WikiLeaks, then you know that the file has been modified in some way.
How does the blockchain make use of hashes?  Hashes are used in blockchains to represent the current state of the world. The input is the entire state of the blockchain, meaning all the transactions that have taken place so far and the resulting output hash represents the current state of the blockchain. The hash is used to agree between all parties that the world state is one and the same, but how are these hashes actually calculated?
The first hash is calculated for the first block or the Genesis block using the transactions inside that block. The sequence of initial transactions is used to calculate a block hash for the Genesis block. For every new block that is generated afterward, the previous block’s hash is also used, as well as its own transactions, as input to determine its block hash. This is how a chain of blocks is formed, each new block hash pointing to the block hash that came before it. This system of hashing guarantees that no transaction in the history can be tampered with because if any single part of the transaction changes, so does the hash of the block to which it belongs, and any following blocks’ hashes as a result. It would be fairly easy to catch any tampering as a result because you can just compare the hashes. This is cool because everyone on the blockchain only needs to agree on 256 bits to represent the potentially infinite state of the blockchain. The Ethereum blockchain is currently tens of gigabytes, but the current state of the blockchain, as of this recording, is this hexadecimal hash representing 256 bits.
What about digital signatures? Digital signatures, like real signatures, are a way to prove that somebody is who they say they are, except that we use cryptography or math, which is more secure than handwritten signatures that can be easily forged. A digital signature is a way to prove that a message originates from a specific person and no one else, like a hacker.
Digital signatures are used today all over the Internet. Whenever you visit a website over ACTPS, you are using SSL, which uses digital signatures to establish trust between you and the server. This means that when you visit Facebook.com, your browser can check the digital signature that came with the web page to verify that it indeed originated from Facebook and not some hacker.
In asymmetric encryption systems, users generate something called a key pair, which is a public key and a private key using some known algorithm. The public key and private key are associated with each other through some mathematical relationship. The public key is meant to be distributed publicly to serve as an address to receive messages from other users, like an IP address or home address. The private key is meant to be kept secret and is used to digitally sign messages sent to other users. The signature is included in the message so that the recipient can verify using the sender’s public key. This way, the recipient can be sure that only the sender could have sent this message. Generating a key pair is analogous to creating an account on the blockchain, but without having to actually register anywhere. Pretty cool. Also, every transaction that is executed on the blockchain is digitally signed by the sender using their private key. This signature ensures that only the owner of the account can move money out of the account.
To bring it all together, blockchain could not exist without hashing and digital signatures. Hashing provides a way for everyone on the blockchain to agree on the current world state, while digital signatures provide a way to ensure that all transactions are only made by the rightful owners. We rely on these two properties to ensure that the blockchain has not been corrupted or compromised.

Continue Reading
No comments
Share:

Introduction to Solidity: ACL and Events. [Part 2]

This article is next in series to the previous one that talked about data contracts. The example contract in the previous discussion was inheriting from a contract called “ACLContract”, but we were not using any feature provided by the ACLContract as we were yet to see how ACL (Access Control List) and “eventing” could be used to deliver access control and access logging facility.
Access control is a mechanism to provide selective restrict access to a resource. There are various kinds of access control models in Information technology, most of them center around the user or “principal” that is attempting to access the resource. There are situations where the resource itself can define access to it, but we will not go into that one. For our purpose, we will stick to two kinds of access controls – Role-based and attribute-based.

Inheritance:

Since access control is a feature that should be pluggable to some extent, we will leverage inheritance to provide this feature to your domain contracts. Inheritance in solidity uses the copy code mechanism to plant the “super-contract” code into “subcontract”- super-contract being the inheritable contract and sub-contract being the inheriting contract. Solidity also supports an Object Oriented Programming (OOPS) concept of polymorphism, where a contract instance can double up as any of its subclass instances.
Our ACL (Access Control List) contract is going to be inherited by a domain contract and will provide data access control features. The domain contract will just have to surround its resource calls with the ACL contract methods that it will inherit.

ACL contract:

The basic premise of the ACL contract is to provide methods to create/manage a list or lists of users and to provide methods that can check any specific user against that list. Our assumption is that each user of a contract is an “address” type – the address is a special type of variable in the solidity that represents your wallet or account address. It makes sense to use it as a user credential as a user only accesses a contract by his account address. We can also draw an assumption that the call from an address is authentic as it can only be made if the user has access to the private key of the account, which is the basic premise of authenticity on ethereum.  
The basic template of the contract is going to have two instance variables:
address public owner;     

address [] public users;
The owner's address will be the creator of the contract. We will instantiate it during the constructor call. This is a fair assumption as the owner should be only deploying the contract unless we need to delegate the owner functions to another address, for which we will make provisions within the contract as we will see.
So if the contract is called ACLContract, the following code will instantiate the owner's address and also make the owner as one of the users.
function ACLContract() {
    owner = msg.sender;
    users.push(owner);
}
Once we instantiate the contract, we will need some operation methods to administer the list of users. The msg is a special type of object in the solidity that holds data about the caller or sender of a transaction. In this case, the deployer account will the caller of the transaction that deploys the contract, so we will assign that owner address to this caller’s address.
function addUser(address user){
       if (msg.sender != owner) throw;
       users.push(user);

}

   

function getIthUser(uint i) constant returns (address){
    return users[i];

}

   

function getUserCount() constant returns (uint){
       return users.length;

}

   

function deleteIthUser(uint i){
        if (msg.sender != owner) throw;
       delete users[i];

}

These methods will be used by clients to manage the user’s list. We see that only the owner will have the ability to administer the list with this check:
if (msg.sender != owner) throw;
So this code matches the caller address with the owner and fails the transactions with a throw-in case there is a mismatch. Before we move further we need to look a bit at throwing exceptions as this is the main protection we will put in case our access control mechanism fails.

Exceptions:

Exceptions are the mechanism in solidity to indicate an error situation in a transaction. The result of an exception is that the current call is stopped, and all the effects of the transaction are reversed. If the exception occurs in a call stack, then the exception is returned up the stack to the first caller. Currently, it’s not possible to recover from the exception in solidity, as the partial state change that has occurred may not be safe to continue the transaction, so to maintain the atomicity of the transaction, all changes are reverted.
There are two kinds of exceptions, runtime exceptions, and user-provided exceptions.
Runtime exceptions occur automatically in case the code encounters the 12 situations listed in the solidity documentation (please refer to the documentation – too voluminous and redundant to paste here), those are mostly anomalies that might occur in the state of the statement/transaction being executed is successful.
User-provided exceptions are throwing manually in code. There are two ways to create them – using require a condition that turns out to be false or using an explicit throw. We are using the conditional throw, and as we want this will revert the transaction effects and fail the call in case of violation of the access control that is put in place.
Coming back to our ACLContract, we have completed the creation of the list of users and the methods that we need to administer it. There are some caveats to what we did, it’s possible to create two lists – one for read-only users, and another one for reading and write users.
The fact is any data that is there in ethereum blockchain is public in nature, so its doesn’t make sense to create a read-only users, as anyone can see that data, but in case where the data access is encrypted in a way that allows it to be linked to user account then we can think of a read-only user. There are discussions on in the ethereum community to make ethereum blockchain privacy-friendly, and there are multiple proposals on how that can be done.
If we can draw an assumption that with any of those proposals, or through a custom scheme we are able to encrypt our data and we are able to ensure that data access can only be done throughout contract code, then we will find it useful to create two lists – a read-only user and a read-write user. The code for that will be very similar to what we have written for our single array users. We will just need four administration methods for each list (readUsers and writeUsers).

Creating access Control:

To vet a user against the access control list, we need to match it with the list of addresses. We can create a simple method that accepts a user address and tries to match it with the list:
function isUser(address candidate, string method) returns (bool){

  for(uint8 i = 0; i < users.length; i++){

            

            if (users[i] == candidate){               

              return true;

            }

         }      

      return false;

    }

The logic is simple to understand if we find the user in the list, we exit the loop with true, if we run out of elements in the list, then return false. The string method parameter that is passed is going to be used later when we talk about eventing to log the access of the user and the result of the access attempt.

Logging Access Using Events:

The basic concept defined in security principles is AAA (Authentication, Authorization, and Auditing).
The authentication is provided by ethereum when the user initiates a transaction with a certain account. It is assumed that the user owns the account as he is able to use it to initiate the transaction. The responsibility of that validation which is results in the authentication of the user with his account password is done at the ethereum node client level.
The Authorization part of the AAA has been implemented by the ACLContract where Role-based access control is enforced.
The third part of AAA is Auditing- The requirement of auditing is that user access should be logged. To do this we will use Events.

Solidity Events:

Events are just like normal instance variables of a contract, they can be inherited like any variable. Events are used to return values to the client in case a list of values is to be returned, but we will only examine them as a means to create logs on the blockchain. Events when they are “fired” from a part of the blockchain with the parameters that are supplied to them.
To implement a log event we will define an Event variable:
event LogAccess(address indexed by, uint indexed accessTime, string method, string desc);

This event will be used in our access control method isUser() to log the access that is being attempted with its result.

function isUser(address candidate, string method) returns (bool){

        for(uint8 i = 0; i < users.length; i++){

            

            if (users[i] == candidate){

              LogAccess(candidate, now, method, "successful access");

              return true;

            }

         }

      LogAccess(candidate, now,method,  "failed access");

      return false;

    }

The event is parameterizing the accessing account (candidate) the time, (now) the resource (method) and the result (failed access, successful access). We are using a string to describe the result, but it’s recommended to use uint constants to enable the easier search.
The event will be fired each time isUser() is accessed and will log the access on the blockchain for audit purposes.   The events can be accessed by a web3 client call which we will see in the following section.

Putting ACLContract to use:

The contract that we created can be inherited by any other contract to reuse the ACL lists provided by it. Our data contract was inheriting it using the construct.
contrat DataContract is ACLContract {



To use the ACL facility, we will be intercepting the method calls in the contract with the isUser() :



function updateCustomer(uint index, string name) {

if (isUser(msg.sender, "updateCustomer")) {

          if (index > count) throw;

           customers[index].name = name;

}

else throw;

}



function updateCustomerStatus(uint index, uint status) {

if (isUser(msg.sender, "updateCustomer")) {

       if (index > count) throw;

       customers[index].status = status;

        }  

else throw;

}



function createCustomer(

uint id,

string name,

uint dateOfBirth,

uint social){

       if (isUser(msg.sender, "createCustomer")) {

        customers[count] = Customer(id, name, dateOfBirth, social, pending);

        count++;

         }

else throw;

}

We are only supplying Access Control restrictions to methods that update the data, if we had encrypted the customer data within the contract, we could implement restriction on its read capabilities too.
The contract cannot access the events that it creates, so to access the events, we will need our web3 client to create a call:
Assuming the ABI has contracted ABI and address is its location on the blockchain.
var DataContract = web3.eth.contract(abi).at(address);

var eventLogs = DataContract.allEvents().get();

console.log(eventLogs);
There is a lot more to events than how we are using it above, our objective is to retrieve them for auditing purposes.

Attribute-based Access Control:

It’s possible to have another type of access control where authorized users are identified by an attribute. We are discussing this to exemplify the “Attribute-based access control” we talked about in the introduction.  This is just a variation of the isUser() call:
function isUserAuthorized(address candidate, string method) returns (bool){

        for(uint8 i = 0; i < users.length; i++){

            

            if (candidate.balance > 100){

              LogAccess(msg.sender, now, method, "successful access");

              return true;

            }

         }

      LogAccess(msg.sender, now,method,  "failed access");

      return false;

    }

This is a very trivial example where an authorized user is the one who has a balance ether greater than 100.

Continue Reading
No comments
Share:

Introduction to Solidity: Creating a data contract [Part 1]

Solidity is a javascript like a language used to code smart contracts on the Ethereum platform. It compiles into a bytecode format that is understood by the Ethereum Virtual machine (EVM). It’s a strongly typed language with the ability to define custom data structures. Introduction to Solidity part 1 will teach you to utilize a subset of solidity functionality to create a template of a smart contract that can be re-applied to formulate a complete set of contracts that house data and basic logic that works for any domain. This will be a multi-part series as it will cover basic contract design and some related concerns.

Introduction to Solidity: Creating an environment

To execute smart contracts, we need a system that is able to compile, deploy and call its methods. For all the three we have a very simple integrated browser-based app here.
It is possible to use this tool to connect with a live Ethereum node or to form a mock environment. This environment can also easily execute some test cases on the contract methods. It doesn’t need any installation and is completely browser-based. I have used it on chrome over ubuntu, but I’m sure it works just as well on other platforms. The left pane of the app is where the contract code is, and the right side has deployment and test options. The app can work on contract files from own systems.
The source code of the contract we will be discussing is available here. Some parts of the contract code are going to be discussed in the later parts of the series. The code and be downloaded and loaded into Remix to view the sections that are discussed below. Solidity latest unreleased version is 4.10 nightly and we will be relying on features supported by that specific version.

DataContract (Basic data structure):

A data contract is not standard terminology. There multiple types (patterns) of smart contracts defined on Monax (earlier Eris industries) documentation. The “data” type of contract is a simple concept where data is added, updated, removed and accessed. In the process of creating a data contract, we will be able to work with an Access Control List (ACL) contract which can be used to manage role-based security on all contract types, Eventing mechanisms for logging and returning data and some other features of smart contracts.
To create a simple data contract, assume a user-defined high-level data set for e.g. Customers
To simplify, we structure a simple Customer whom we assume to be an individual:

struct Customer{
uint id;

string name;

uint dateOfBirth;

uint social;

uint status;

}

Data Status

We are implementing the struct with the assumption that each data record will have a status. It is not feasible to delete and record and rearrange the entire collection, so status is an attribute that we will leverage to define a state for the record. Contracts in different domains will have a different set of status. As a simple assumption we are following 3 statuses (This is with the thought that a customer might be pending verification, active or might be deleted):
uint constant active = 1;

uint constant pending = 2;

uint constant deleted = 3;

A deleted record for any reference data type on a blockchain should never get hard deleted, so it is an appropriate design practice to assign a status to each record.
Our objective is to enable a collection of Customer struct instances on the blockchain and facilitate the ability to access a specific customer, the list of call customers, and update a specific customer instance. A cross-cutting concern with these objectives is to enable logging and implementing an Access Control Strategy.

To create a collection we will leverage the mapping construct.

mapping (uint => Customer) customers;
mapping (uint => Customer) customers;
This mapping is the template for a map like structure that creates a map of key values where the key is an unsigned int and value is an instance of a customer. This mapping has some limitations, which is that there is no way to loop through it to retrieve all the values. We can only access the elements through a specific get logic:
customers[key];
Due to this, we will have to maintain a shadow key to maintain a count of elements in the mapping and retrieve it based on the count.
public uint count = 0;
Now we have our data structure ready that we will be used to house the customer data.

Data Contract (Data Creation):

To create a customer instance and key it off we will implement a method that will accept constituent data.
function create Customer(uint id, string name, uint dateOfBirth, uint social){

customers[count] = Customer(id, name, dateOfBirth, social, pending);

count++;

}

The above method adds data to the mapping and increments the shadow key count. What is to be noted is that we are using the same shadow key to key off the data.
To access data randomly, we will need to supply a specific key against which we have keyed off the data.
function get customer(uint index)
constant returns (uint id, string name, uint dateOfBirth, uint social, uint status)

{

id = customers[index].id;

name = customers[index].name;

dateOfBirth = customers[index].dateOfBirth;

social = customers[index].social;

status = customers[index].status;

}

This method is a constant one as it does not change the state of the contract data (it’s a read-only method). So to call this method we will not need any gas.
To access all the customers we will have to leverage the count shadow key. We will need to implement the looping structure on the client and reuse the index-based call above. This will be explained by the contract client explanation.
To access the customer based on a specific attribute in a struct, We will have to implement a loop-based brute search. There are more efficient ways to reading it using parsing the transaction that was responsible for creating that data.
function getCustomerById(uint id)
constant returns (uint idRet, string name, uint dateOfBirth, uint social, uint status)

{

for (var i=0; i&lt; count; i++)

{

if (customers[i].id == id) {

idRet = customers[i].id;

name = customers[i].name;

dateOfBirth = customers[i].dateOfBirth;

social = customers[i].social;

status = customers[i].status;

return;

}

}

}

This is a very inefficient way to retrieve the customer from an attribute value. There are also other issues with this method apart from inefficiency. It’s not possible to easily match strings in solidity, so it’s not possible to match string attributes. Also, it returns the first match, it’s not possible to return a list of matches. We will go into more efficient methods to access this data in later parts of this series.

Data Contract (Data Update):

The update data method is simply the reverse of the access method. The only thing to remember is that this method results in a change for the blockchain state so the changes will only reflect once the transaction is confirmed. We will discuss how to ensure that the transaction is confirmed before we try to access the data in the later part of our series.

function updateCustomer(uint index, string name) {

customers[index].name = name;

}
It makes sense to put some checks for index value (It has to be less than the count)
function updateCustomer(uint index, string name) {

if (index &gt; count) throw;

customers[index].name = name;

}

function updateCustomerStatus(uint index, uint status) {

if (index &gt; count) throw;

customers[index].status = status;

}

The different methods should be implemented for updating each attribute, here we are updating the name. The method updateCustomerStatus() should be treated as a special method that can enable or disable records.
It’s possible to add the same check on the access method that accesses the index key, but it’s not necessary as the return will null in case the invalid index is supplied, so the client should be able to validate the response and return suitable errors. Since access would be a more frequently called method set, it should be made as efficient as possible.

Testing the contract:

To test the contract, go to the environment tab on the right panel (the box icon).
You will see the contract listed on the right with the option to provide an address (At Address) and an option to Create. Select the javascript VM radio button (Selected by default and hit create). This will create a local in-browser environment for you to execute tests on your contract and event debug it.

Introduction to Solidity: Creating a data contract [Part 1]

Introduction to Solidity: Creating a data contract [Part 1]

This test environment gives you the ability to call contract methods individually and see the results on the data.
To start with let’s call the create Contract method to add some data onto the blockchain (not the real one yet, but mock one).
Look for the red marked button with the method call createCustomer and add parameters to the text field next to it separated by commas like you would if you were calling this method through a javascript client. For e.g. (For simplicity we have chosen dateOfBirth to be of the unit timestamp which can fit into a unit)
For e.g. (For simplicity we have chosen dateOfBirth to be of the unit timestamp which can fit into a unit)

101, "Jack", 845078400, 1234567

With this parameter set, click the create customer and you should see the following printed out below the call:



Result: "0x"

Transaction cost: 129390 gas.

Execution cost: 106454 gas.

This will indicate that the method call has been successful, you can confirm it by checking the count of the customers by hitting the count button (The method call count()). Remember that solidity exposes its public members through a direct call with the signature member().
The call should print out something like:
"0x0000000000000000000000000000000000000000000000000000000000000002"

Transaction cost: 21505 gas. (caveat)

Execution cost: 233 gas.

Decoded:

uint256: 1

This uint256 has a value 1 which indicates that you have a single member in your recordset.
You can run the above createCustomer call multiple times and verify the result. Beware that there is no check on adding duplicate records. This has to be checked by the client.
You can retrieve the customer using the index-based getCustomer(0) – remember your index starts with 0. You should see output like this:
Value:

"0x000000000000000000000000000000000000000000000000000000000000006500000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000325edf80000000000000000000000000000000000000000000000000000000000012d687000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000044a61636b00000000000000000000000000000000000000000000000000000000"

Transaction cost: 23404 gas. (caveat)

Execution cost: 2004 gas.

Decoded:

uint256 id: 101
string name: Jack
uint256 dateOfBirth: 845078400
uint256 social: 1234567
uint256 status: 2

The value being returned is the encoded data that is returned. It is decoded and displayed and parameter values in the sequence below.
Now you have a complete working contract that has been tested against some test data.
There are situations when your contract does not work as expected, in which case you have to debug the contract to find out the state of the contract data as a method executes and identifies the problem. There is currently no solidity debugger. There is a solidity IDE – Mix which has the capability, but it is currently not being supported. You can test it out at your own risk.
Now to deploy your contract to a real ethereum instance and call it using a simple javascript client.

Deploying the contract:

You can refer to a previous article on how to set up a local ethereum node using parity. We will use this capability and assume that you have a local running ethereum instance that exposes JSON_RPC port on 8545. We also assume that you have an account created and is returned at accounts[0] location, also this account should have enough ether balance to deploy the contract and execute transaction calls with the gas charges.
The remix IDE gives you the ability to deploy this contract directly from the IDE into the ethereum instance. To do that you have to first select the Web3 provider option from the Environment tab. If the environment is currently picked up you will not see any error below the contract.
Screen_3 (Contract deploy option)
Introduction to Solidity: Creating a data contract [Part 1]

The IDE gives you three outputs from the contract compilation process BTW the contract is automatically compiled. Ensure you see the options as shown in Screen _3. else it means that compilation has failed, and you should see the compilation error.
The Bytecode is the EVM code that is created when your code is compiled. This is the low-level instruction set that ethereum understands. The second is the Application Binary interface or the ABI of the contract code. ABI is just a list of method signatures, return types, members, etc of the contract in a defined JSON format. This ABI is needed when you will call your contract from a real javascript client.
The third option Web3 deploy is the option that lets you push the contract directly onto the node instance. Just select this option and you should see your contract address on the blockchain returned to you.. (Like sreen_2). This contract address is important as it’s needed in the javascript client that you will shortly create. In case you are unable to deploy the contract directly into the blockchain from the ethereum console. Just copy the script in the text area against the web3 deploy option and paste onto the console. You should see tone console.log output with “contract mined” followed by its address on the chain.

Running the contract from a real client.

To integrate the contract with your enterprise application code. To do that, you will be creating a simple javascript/Html client that can run in the browser. You can also run this client as a nodejs application. This is something I will cover in the later parts of the series.
To communicate with the ethereum blockchain, ethereum exposes a low-level JSON-RPC interface. This interface accepts transactions to the contract. It is a very low-level interface so it is hard to work with it directly. There is a javascript framework web3.js that allows higher-level contract code abstractions to enable applications to integrate with contract calls.
To enable web3 in a browser-supported environment, a single script file needs to be referenced within the page code to interact with the contract.
<script src=”path/to/web3.js”>
Web3.js is available for download from the links in the documentation referred to above. Web3 generates a handle to contract instance on ethereum to enable all method calls that we implemented in our solidity source. These method calls can be coded as if there is a direct javascript reference to the method script. This is enabled by the JSON-RPC interface.
There are is a templated approach available to get a contract handle. The first thing that is needed is to instantiate web3 and supply the contract ABI to it.
var Web3 = require('web3');

var web3 = new Web3();

web3.setProvider(<span lang="zxx"><a href="http://localhost:8545/">http://localhost:8545</a></span>);

web3.eth.defaultAccount=web3.eth.accounts[0];
The provider URL is your local JSON_RPC interface. The default account setting is the ethereum wallet which will be used for as the from the account when we will execute the transactions on the contract. We need to ensure that the account is unlocked if we are using geth node instance as by default the account is locked every 30 seconds after its unlocked.
The next step is to instantiate the contract blueprint by supplying the contract ABI so web3.
var customerContract = web3.eth.contract([ABI JSON]).
The ABI JSON array is usually a long JSON string so we are just paraphrasing, but you should be copying the entire ABI array from the Interface text area as shown in screen3. Once you have the customer contract blueprint, we need to instantiate it by supplying the real address at which the contract resides on the blockchain.
var customerContractObject = customerContract.at(‘0x76bd9986c5c3e00111c82e16e01e282696d2b3fb’);
This address would be what you got when you deployed the contract from the web3 deploy or from the ethereum console. Once you have the contract handle linked back to the deployment address, you can execute contract methods by sending transactions to the address. For example, let’s say you want to add customer record after your Html form accepts inputs for the form values from the user, then your Html + web3 code would look something like this:
<html>

<head>

<link rel=stylesheet type=text/css href=style.css>

<script type=text/javascript src=/usr/local/lib/node_modules/web3/dist/web3.js><script type=text/javascript src=jquery.js></script>

<script type=text/javascript>

var Web3 = require(web3);

var web3 = new Web3();

web3.setProvider(new web3.providers.HttpProvider()); //this is for default  localhost:8545

web3.eth.defaultAccount= web3.eth.accounts[0];

var customerContract = web3.eth.contract([ABI JSON]);

var customerContractObject = customerContract.at(0x76bd9986c5c3e00111c82e16e01e282696d2b3fb);

function register(){

var txn = customerContractObject.createCustomer($(id).val(), $ (name).val(), $(dob).val(), $(social).val(), {gas:144840});

console.log(txn);

}

</script>

</head>

<body>

<input type=number name=id id=id placeholder=Customer Id />

<input type=text name=name id=name placeholder=Customer Name />

<input type=date name=dob id=dob placeholder=Customer Date Of Birth />

<input type=number name=social id=social placeholder=Customer Social Security Number />

<input type=button value=Register onclick=register();/>

</body>

</html>
The above code will work out of the box if you fix the path to web3.js and jquery. Just as we have called the method on the contract handle:
var txn = customerContractObject.createCustomer($(id).val(), $ (name).val(), $(dob).val(), $(social).val(), {gas:144840});
It’s possible to call all the other methods. The estimated gas needs to be entered from the test method calls, this is 144840 in my configuration. The above call returns a transaction Id for the transaction that is created on the blockchain to execute this method. This transaction is now a part of the blockchain and can be referred to whenever we want to audit when, how and by whom was this customer created.
There are two types of calls, as we have seen during the coding of the contract. One which updates the state of the contract like createCustomer, updateCustomer etc. And others which are read-only and are marked as constant. The former always return a transaction Id hash, transaction Id hash is a 64-byte identification of the transaction that can be used to refer back to the transaction. If we are running the contract in a synchronous way as we are doing here. The latter returns the actual values that are sought in a comma-separated array. For example the call:
var customer = customerContractObject.getCustomer($(index).val());

console.log(customer)

Will log an array of values like this - 101, "Jack", 845078400, 1234567

In the next part of the series, we will see how some non-functional concerns and aspects are built into the contract-like access control, event logs, contract deletion. We will discuss parts of the contract that specifically deal with these issues.

Continue Reading
No comments
Share: