Create and Sign Msix installer for Flutter Windows-build Files

Msix .A command-line tool that create Msix installer for your flutter windows-build files.

:clipboard: Install

In your pubspec.yaml, add msix as a new dependency.

dev_dependencies:
  flutter_test:
    sdk: flutter
  msix: ^2.2.3

:package: Create Msix

Run:

PS c:\src\flutter_project\> flutter build windows
PS c:\src\flutter_project\> flutter pub run msix:create

The flutter build windows is required to build the executable that flutter pub run msix:create bundles up in the MSIX install file.

:mag: Configuration (Optional)

This tool come with default configuration (test values), you can configure it to suit your needs.

Add msix_config: configuration at the end of your pubspec.yaml file:

msix_config:
  display_name: MyApp
  publisher_display_name: MyName
  identity_name: MyCompany.MySuite.MyApp
  msix_version: 1.0.0.0
  certificate_path: C:\<PathToCertificate>\<MyCertificate.pfx>
  certificate_password: 1234 (require if using .pfx certificate)
  publisher: CN=My Company, O=My Company, L=Berlin, S=Berlin, C=DE
  logo_path: C:\<PathToIcon>\<Logo.png>
  start_menu_icon_path: C:\<PathToIcon>\<Icon.png>
  tile_icon_path: C:\<PathToIcon>\<Icon.png>
  vs_generated_images_folder_path: C:\<PathToFolder>\icons
  icons_background_color: transparent (or some color like: '#ffffff')
  architecture: x64
  capabilities: 'internetClient,location,microphone,webcam'

Available Configuration Fields:

Configuration NameDescription (from microsoft docs)Example Value And TypeRequired
display_nameA friendly name that can be displayed to users.MyApp (string)No
publisher_display_nameA friendly name for the publisher that can be displayed to users.MyName (string)require if uploading to windows store
identity_nameDescribes the contents of the package.com.flutter.MyApp (string)require if uploading to windows store
msix_versionThe version number of the package.1.0.0.0 (must be four numbers with dots)require if uploading to windows store
certificate_pathC:/<PathToCertificate>/<MyCertificate.pfx> No
certificate_passwordthe certificate password1234 (string)require if using .pfx certificate
publisherDescribes the publisher information. The Publisher attribute must match the publisher subject information of the certificate used to sign a package.CN=My Company, O=My Company, L=Berlin, S=Berlin, C=DE (string)require if uploading to windows store
logo_pathAn icon used as the app logo, sample: C:/<PathToIcon>/<Logo.png> No
start_menu_icon_pathAn icon used as the app logo in the start-menu, sample: C:/<PathToIcon>/<Icon.png> No
tile_icon_pathAn icon used as the app tile logo in the start-menu, sample: C:/<PathToIcon>/<Icon.png> No
assets_directory_pathAssets folder (like .dll files) to include in the Msix installerC:\<PathToFolder>\myAssets (string)No
vs_generated_images_folder_pathVisual Studio can generate for you optimized icons (logo/tile and more) see Thomas's explanation. This is an alternative for logo_path, start_menu_icon_path, tile_icon_pathC:\<PathToFolder>\icons (string)No
icons_background_colorSpecifies the background color of the app icons, can be transparent or some color like: '#ffffff'transparent (string)No
languagesDeclares a language for resources contained in the package. sample: en-us, ja-jpen-us (string)No
architectureDescribes the architecture of the code contained in the package, one of: x86, x64, arm,, neutralx64 (string)No
signtool_optionsSigntool using this syntax: [command] [options] [file_name], you can provide here the [options] part, see full documentation here: https://docs.microsoft.com/en-us/dotnet/framework/tools/signtool-exe this option is overwriting the fields: certificate_path, certificate_password/v /fd SHA256 /f C:/Users/me/Desktop/my.cer (string)No
file_extensionFile extensions that the app will used to open.txt, .myFile, .test1 (string)No
protocol_activationProtocol activation that will open and use the apphttp (string)No
capabilitiesList of the capabilities that the application requires. availables capabilities can be found here: App capability declarationsinternetClient,location,microphone,bluetooth,webcam (string)No
storeIf the msix file is intended for publish in Windows Storefalse (boolean) 

Signing Options

before using the msix file, we sign it with certificate, this plugin use signtool to sign the file with default test certificate. you can use your own certificate, see the documentation on the configuration fields:

  • certificate_path
  • certificate_password
  • publisher
  • signtool_options

Also see how to create you own certificate (pfx) in SahajRana's Medium post

:label: Windows Store

If you publish your msix to Windows Store you dont need to sign it, Windows Store does it for you. To generate msix file for Windows Store use the --store flag or add store: true in msix configuration sction in your pubspec.yaml.

Note:

the configuration values publisher_display_name, identity_name, msix_version, publisher must be valid, you can find those values in your Windows Store Dashboard > Product > Product identity.

For more information, please see this tutorial: How to publish your MSIX package to the Microsoft Store

:gear: Command-Line Arguments

You can configuration values with command-line arguments instead of pubspec.yaml or combine them, see full list of arguments and example on this page

:question: Signing Error

For signing problems (signtool) try to get help on this page

package tags: msi windows win10 windows10 windows store windows installer windows packaging appx AppxManifest SignTool MakeAppx

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add msix

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  msix: ^2.3.0

Alternatively, your editor might support or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:msix/msix.dart'; 

Download Details:

Author: YehudaKremer

Source Code: https://github.com/YehudaKremer/msix

#flutter 

What is GEEK

Buddha Community

Create and Sign Msix installer for Flutter Windows-build Files

Google's Flutter 1.20 stable announced with new features - Navoki

Flutter Google cross-platform UI framework has released a new version 1.20 stable.

Flutter is Google’s UI framework to make apps for Android, iOS, Web, Windows, Mac, Linux, and Fuchsia OS. Since the last 2 years, the flutter Framework has already achieved popularity among mobile developers to develop Android and iOS apps. In the last few releases, Flutter also added the support of making web applications and desktop applications.

Last month they introduced the support of the Linux desktop app that can be distributed through Canonical Snap Store(Snapcraft), this enables the developers to publish there Linux desktop app for their users and publish on Snap Store.  If you want to learn how to Publish Flutter Desktop app in Snap Store that here is the tutorial.

Flutter 1.20 Framework is built on Google’s made Dart programming language that is a cross-platform language providing native performance, new UI widgets, and other more features for the developer usage.

Here are the few key points of this release:

Performance improvements for Flutter and Dart

In this release, they have got multiple performance improvements in the Dart language itself. A new improvement is to reduce the app size in the release versions of the app. Another performance improvement is to reduce junk in the display of app animation by using the warm-up phase.

sksl_warm-up

If your app is junk information during the first run then the Skia Shading Language shader provides for pre-compilation as part of your app’s build. This can speed it up by more than 2x.

Added a better support of mouse cursors for web and desktop flutter app,. Now many widgets will show cursor on top of them or you can specify the type of supported cursor you want.

Autofill for mobile text fields

Autofill was already supported in native applications now its been added to the Flutter SDK. Now prefilled information stored by your OS can be used for autofill in the application. This feature will be available soon on the flutter web.

flutter_autofill

A new widget for interaction

InteractiveViewer is a new widget design for common interactions in your app like pan, zoom drag and drop for resizing the widget. Informations on this you can check more on this API documentation where you can try this widget on the DartPad. In this release, drag-drop has more features added like you can know precisely where the drop happened and get the position.

Updated Material Slider, RangeSlider, TimePicker, and DatePicker

In this new release, there are many pre-existing widgets that were updated to match the latest material guidelines, these updates include better interaction with Slider and RangeSliderDatePicker with support for date range and time picker with the new style.

flutter_DatePicker

New pubspec.yaml format

Other than these widget updates there is some update within the project also like in pubspec.yaml file format. If you are a flutter plugin publisher then your old pubspec.yaml  is no longer supported to publish a plugin as the older format does not specify for which platform plugin you are making. All existing plugin will continue to work with flutter apps but you should make a plugin update as soon as possible.

Preview of embedded Dart DevTools in Visual Studio Code

Visual Studio code flutter extension got an update in this release. You get a preview of new features where you can analyze that Dev tools in your coding workspace. Enable this feature in your vs code by _dart.previewEmbeddedDevTools_setting. Dart DevTools menu you can choose your favorite page embed on your code workspace.

Network tracking

The updated the Dev tools comes with the network page that enables network profiling. You can track the timings and other information like status and content type of your** network calls** within your app. You can also monitor gRPC traffic.

Generate type-safe platform channels for platform interop

Pigeon is a command-line tool that will generate types of safe platform channels without adding additional dependencies. With this instead of manually matching method strings on platform channel and serializing arguments, you can invoke native class and pass nonprimitive data objects by directly calling the Dartmethod.

There is still a long list of updates in the new version of Flutter 1.2 that we cannot cover in this blog. You can get more details you can visit the official site to know more. Also, you can subscribe to the Navoki newsletter to get updates on these features and upcoming new updates and lessons. In upcoming new versions, we might see more new features and improvements.

You can get more free Flutter tutorials you can follow these courses:

#dart #developers #flutter #app developed #dart devtools in visual studio code #firebase local emulator suite in flutter #flutter autofill #flutter date picker #flutter desktop linux app build and publish on snapcraft store #flutter pigeon #flutter range slider #flutter slider #flutter time picker #flutter tutorial #flutter widget #google flutter #linux #navoki #pubspec format #setup flutter desktop on windows

Terry  Tremblay

Terry Tremblay

1598396940

What is Flutter and why you should learn it?

Flutter is an open-source UI toolkit for mobile developers, so they can use it to build native-looking** Android and iOS** applications from the same code base for both platforms. Flutter is also working to make Flutter apps for Web, PWA (progressive Web-App) and Desktop platform (Windows,macOS,Linux).

flutter-mobile-desktop-web-embedded_min

Flutter was officially released in December 2018. Since then, it has gone a much stronger flutter community.

There has been much increase in flutter developers, flutter packages, youtube tutorials, blogs, flutter examples apps, official and private events, and more. Flutter is now on top software repos based and trending on GitHub.

Flutter meaning?

What is Flutter? this question comes to many new developer’s mind.

humming_bird_dart_flutter

Flutter means flying wings quickly, and lightly but obviously, this doesn’t apply in our SDK.

So Flutter was one of the companies that were acquired by **Google **for around $40 million. That company was based on providing gesture detection and recognition from a standard webcam. But later when the Flutter was going to release in alpha version for developer it’s name was Sky, but since Google already owned Flutter name, so they rename it to Flutter.

Where Flutter is used?

Flutter is used in many startup companies nowadays, and even some MNCs are also adopting Flutter as a mobile development framework. Many top famous companies are using their apps in Flutter. Some of them here are

Dream11

Dream11

NuBank

NuBank

Reflectly app

Reflectly app

Abbey Road Studios

Abbey Road Studios

and many more other apps. Mobile development companies also adopted Flutter as a service for their clients. Even I was one of them who developed flutter apps as a freelancer and later as an IT company for mobile apps.

Flutter as a service

#dart #flutter #uncategorized #flutter framework #flutter jobs #flutter language #flutter meaning #flutter meaning in hindi #google flutter #how does flutter work #what is flutter

Riyad Amin

Riyad Amin

1571046022

Build Your Own Cryptocurrency Blockchain in Python

Cryptocurrency is a decentralized digital currency that uses encryption techniques to regulate the generation of currency units and to verify the transfer of funds. Anonymity, decentralization, and security are among its main features. Cryptocurrency is not regulated or tracked by any centralized authority, government, or bank.

Blockchain, a decentralized peer-to-peer (P2P) network, which is comprised of data blocks, is an integral part of cryptocurrency. These blocks chronologically store information about transactions and adhere to a protocol for inter-node communication and validating new blocks. The data recorded in blocks cannot be altered without the alteration of all subsequent blocks.

In this article, we are going to explain how you can create a simple blockchain using the Python programming language.

Here is the basic blueprint of the Python class we’ll use for creating the blockchain:

class Block(object):
    def __init__():
        pass
    #initial structure of the block class 
    def compute_hash():
        pass
    #producing the cryptographic hash of each block 
  class BlockChain(object):
    def __init__(self):
    #building the chain
    def build_genesis(self):
        pass
    #creating the initial block
    def build_block(self, proof_number, previous_hash):
        pass
    #builds new block and adds to the chain
   @staticmethod
    def confirm_validity(block, previous_block):
        pass
    #checks whether the blockchain is valid
    def get_data(self, sender, receiver, amount):
        pass
    # declares data of transactions
    @staticmethod
    def proof_of_work(last_proof):
        pass
    #adds to the security of the blockchain
    @property
    def latest_block(self):
        pass
    #returns the last block in the chain

Now, let’s explain how the blockchain class works.

Initial Structure of the Block Class

Here is the code for our initial block class:

import hashlib
import time
class Block(object):
    def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
        self.index = index
        self.proof_number = proof_number
        self.previous_hash = previous_hash
        self.data = data
        self.timestamp = timestamp or time.time()
    @property
    def compute_hash(self):
        string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
        return hashlib.sha256(string_block.encode()).hexdigest()

As you can see above, the class constructor or initiation method ( init()) above takes the following parameters:

self — just like any other Python class, this parameter is used to refer to the class itself. Any variable associated with the class can be accessed using it.

index — it’s used to track the position of a block within the blockchain.

previous_hash — it used to reference the hash of the previous block within the blockchain.

data—it gives details of the transactions done, for example, the amount bought.

timestamp—it inserts a timestamp for all the transactions performed.

The second method in the class, compute_hash , is used to produce the cryptographic hash of each block based on the above values.

As you can see, we imported the SHA-256 algorithm into the cryptocurrency blockchain project to help in getting the hashes of the blocks.

Once the values have been placed inside the hashing module, the algorithm will return a 256-bit string denoting the contents of the block.

So, this is what gives the blockchain immutability. Since each block will be represented by a hash, which will be computed from the hash of the previous block, corrupting any block in the chain will make the other blocks have invalid hashes, resulting in breakage of the whole blockchain network.

Building the Chain

The whole concept of a blockchain is based on the fact that the blocks are “chained” to each other. Now, we’ll create a blockchain class that will play the critical role of managing the entire chain.

It will keep the transactions data and include other helper methods for completing various roles, such as adding new blocks.

Let’s talk about the helper methods.

Adding the Constructor Method

Here is the code:

class BlockChain(object):
    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.build_genesis()

The init() constructor method is what instantiates the blockchain.

Here are the roles of its attributes:

self.chain — this variable stores all the blocks.

self.current_data — this variable stores information about the transactions in the block.

self.build_genesis() — this method is used to create the initial block in the chain.

Building the Genesis Block

The build_genesis() method is used for creating the initial block in the chain, that is, a block without any predecessors. The genesis block is what represents the beginning of the blockchain.

To create it, we’ll call the build_block() method and give it some default values. The parameters proof_number and previous_hash are both given a value of zero, though you can give them any value you desire.

Here is the code:

def build_genesis(self):
        self.build_block(proof_number=0, previous_hash=0)
 def build_block(self, proof_number, previous_hash):
        block = Block(
            index=len(self.chain),
            proof_number=proof_number,
            previous_hash=previous_hash,
            data=self.current_data
        )
        self.current_data = []  
        self.chain.append(block)
        return block

Confirming Validity of the Blockchain

The confirm_validity method is critical in examining the integrity of the blockchain and making sure inconsistencies are lacking.

As explained earlier, hashes are pivotal for realizing the security of the cryptocurrency blockchain, because any slight alteration in an object will result in the creation of an entirely different hash.

Thus, the confirm_validity method utilizes a series of if statements to assess whether the hash of each block has been compromised.

Furthermore, it also compares the hash values of every two successive blocks to identify any anomalies. If the chain is working properly, it returns true; otherwise, it returns false.

Here is the code:

def confirm_validity(block, previous_block):
        if previous_block.index + 1 != block.index:
            return False
        elif previous_block.compute_hash != block.previous_hash:
            return False
        elif block.timestamp <= previous_block.timestamp:
            return False
        return True

Declaring Data of Transactions

The get_data method is important in declaring the data of transactions on a block. This method takes three parameters (sender’s information, receiver’s information, and amount) and adds the transaction data to the self.current_data list.

Here is the code:

def get_data(self, sender, receiver, amount):
        self.current_data.append({
            'sender': sender,
            'receiver': receiver,
            'amount': amount
        })
        return True

Effecting the Proof of Work

In blockchain technology, Proof of Work (PoW) refers to the complexity involved in mining or generating new blocks on the blockchain.

For example, the PoW can be implemented by identifying a number that solves a problem whenever a user completes some computing work. Anyone on the blockchain network should find the number complex to identify but easy to verify — this is the main concept of PoW.

This way, it discourages spamming and compromising the integrity of the network.

In this article, we’ll illustrate how to include a Proof of Work algorithm in a blockchain cryptocurrency project.

Finalizing With the Last Block

Finally, the latest_block() helper method is used for retrieving the last block on the network, which is actually the current block.

Here is the code:

def latest_block(self):
        return self.chain[-1]

Implementing Blockchain Mining

Now, this is the most exciting section!

Initially, the transactions are kept in a list of unverified transactions. Mining refers to the process of placing the unverified transactions in a block and solving the PoW problem. It can be referred to as the computing work involved in verifying the transactions.

If everything has been figured out correctly, a block is created or mined and joined together with the others in the blockchain. If users have successfully mined a block, they are often rewarded for using their computing resources to solve the PoW problem.

Here is the mining method in this simple cryptocurrency blockchain project:

def block_mining(self, details_miner):
            self.get_data(
            sender="0", #it implies that this node has created a new block
            receiver=details_miner,
            quantity=1, #creating a new block (or identifying the proof number) is awarded with 1
        )
        last_block = self.latest_block
        last_proof_number = last_block.proof_number
        proof_number = self.proof_of_work(last_proof_number)
        last_hash = last_block.compute_hash
        block = self.build_block(proof_number, last_hash)
        return vars(block)

Summary

Here is the whole code for our crypto blockchain class in Python:

import hashlib
import time
class Block(object):
    def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
        self.index = index
        self.proof_number = proof_number
        self.previous_hash = previous_hash
        self.data = data
        self.timestamp = timestamp or time.time()
    @property
    def compute_hash(self):
        string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
        return hashlib.sha256(string_block.encode()).hexdigest()
    def __repr__(self):
        return "{} - {} - {} - {} - {}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
class BlockChain(object):
    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.build_genesis()
    def build_genesis(self):
        self.build_block(proof_number=0, previous_hash=0)
    def build_block(self, proof_number, previous_hash):
        block = Block(
            index=len(self.chain),
            proof_number=proof_number,
            previous_hash=previous_hash,
            data=self.current_data
        )
        self.current_data = []  
        self.chain.append(block)
        return block
    @staticmethod
    def confirm_validity(block, previous_block):
        if previous_block.index + 1 != block.index:
            return False
        elif previous_block.compute_hash != block.previous_hash:
            return False
        elif block.timestamp <= previous_block.timestamp:
            return False
        return True
    def get_data(self, sender, receiver, amount):
        self.current_data.append({
            'sender': sender,
            'receiver': receiver,
            'amount': amount
        })
        return True        
    @staticmethod
    def proof_of_work(last_proof):
        pass
    @property
    def latest_block(self):
        return self.chain[-1]
    def chain_validity(self):
        pass        
    def block_mining(self, details_miner):       
        self.get_data(
            sender="0", #it implies that this node has created a new block
            receiver=details_miner,
            quantity=1, #creating a new block (or identifying the proof number) is awared with 1
        )
        last_block = self.latest_block
        last_proof_number = last_block.proof_number
        proof_number = self.proof_of_work(last_proof_number)
        last_hash = last_block.compute_hash
        block = self.build_block(proof_number, last_hash)
        return vars(block)  
    def create_node(self, address):
        self.nodes.add(address)
        return True
    @staticmethod
    def get_block_object(block_data):        
        return Block(
            block_data['index'],
            block_data['proof_number'],
            block_data['previous_hash'],
            block_data['data'],
            timestamp=block_data['timestamp']
        )
blockchain = BlockChain()
print("GET READY MINING ABOUT TO START")
print(blockchain.chain)
last_block = blockchain.latest_block
last_proof_number = last_block.proof_number
proof_number = blockchain.proof_of_work(last_proof_number)
blockchain.get_data(
    sender="0", #this means that this node has constructed another block
    receiver="LiveEdu.tv", 
    amount=1, #building a new block (or figuring out the proof number) is awarded with 1
)
last_hash = last_block.compute_hash
block = blockchain.build_block(proof_number, last_hash)
print("WOW, MINING HAS BEEN SUCCESSFUL!")
print(blockchain.chain)

Now, let’s try to run our code to see if we can generate some digital coins…

Wow, it worked!

Conclusion

That is it!

We hope that this article has assisted you to understand the underlying technology that powers cryptocurrencies such as Bitcoin and Ethereum.

We just illustrated the basic ideas for making your feet wet in the innovative blockchain technology. The project above can still be enhanced by incorporating other features to make it more useful and robust.

Learn More

Thanks for reading !

Do you have any comments or questions? Please share them below.

#python #cryptocurrency

Adobe XD plugin for Flutter with CodePen Tutorial

Recently Adobe XD releases a new version of the plugin that you can use to export designs directly into flutter widgets or screens. Yes, you read it right, now you can make and export your favorite design in Adobe XD and export all the design in the widget form or as a full-screen design, this can save you a lot of time required in designing.

What we will do?
I will make a simple design of a dialogue box with a card design with text over it as shown below. After you complete this exercise you can experiment with the UI. You can make your own components or import UI kits available with the Adobe XD.

#developers #flutter #adobe xd design export to flutter #adobe xd flutter code #adobe xd flutter code generator - plugin #adobe xd flutter plugin #adobe xd flutter plugin tutorial #adobe xd plugins #adobe xd to flutter #adobe xd tutorial #codepen for flutter.

Crie seu próprio blockchain de criptomoeda em Python

A criptomoeda é uma moeda digital descentralizada que usa técnicas de criptografia para regular a geração de unidades monetárias e para verificar a transferência de fundos. Anonimato, descentralização e segurança estão entre suas principais características. A criptomoeda não é regulamentada ou rastreada por nenhuma autoridade centralizada, governo ou banco.

Blockchain, uma rede ponto a ponto descentralizada (P2P), que é composta por blocos de dados, é parte integrante da criptomoeda. Esses blocos armazenam cronologicamente informações sobre transações e aderem a um protocolo para comunicação entre nós e validação de novos blocos. Os dados gravados em blocos não podem ser alterados sem a alteração de todos os blocos subsequentes.

Neste artigo, vamos explicar como você pode criar um blockchain simples usando a linguagem de programação Python.

Aqui está o projeto básico da classe Python que usaremos para criar o blockchain:

class Block(object):
    def __init__():
        pass
    #initial structure of the block class 
    def compute_hash():
        pass
    #producing the cryptographic hash of each block 
  class BlockChain(object):
    def __init__(self):
    #building the chain
    def build_genesis(self):
        pass
    #creating the initial block
    def build_block(self, proof_number, previous_hash):
        pass
    #builds new block and adds to the chain
   @staticmethod
    def confirm_validity(block, previous_block):
        pass
    #checks whether the blockchain is valid
    def get_data(self, sender, receiver, amount):
        pass
    # declares data of transactions
    @staticmethod
    def proof_of_work(last_proof):
        pass
    #adds to the security of the blockchain
    @property
    def latest_block(self):
        pass
    #returns the last block in the chain

Agora, vamos explicar como a classe blockchain funciona.

Estrutura Inicial da Classe de Bloco

Aqui está o código para nossa classe de bloco inicial:

import hashlib
import time
class Block(object):
    def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
        self.index = index
        self.proof_number = proof_number
        self.previous_hash = previous_hash
        self.data = data
        self.timestamp = timestamp or time.time()
    @property
    def compute_hash(self):
        string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
        return hashlib.sha256(string_block.encode()).hexdigest()

Como você pode ver acima, o construtor de classe ou método de iniciação ( init ()) acima usa os seguintes parâmetros:

self- assim como qualquer outra classe Python, este parâmetro é usado para se referir à própria classe. Qualquer variável associada à classe pode ser acessada usando-a.

index - é usado para rastrear a posição de um bloco dentro do blockchain.

previous_hash - usado para fazer referência ao hash do bloco anterior dentro do blockchain.

data—it dá detalhes das transações realizadas, por exemplo, a quantidade comprada.

timestamp—it insere um carimbo de data / hora para todas as transações realizadas.

O segundo método da classe, compute_hash, é usado para produzir o hash criptográfico de cada bloco com base nos valores acima.

Como você pode ver, importamos o algoritmo SHA-256 para o projeto blockchain de criptomoeda para ajudar a obter os hashes dos blocos.

Uma vez que os valores tenham sido colocados dentro do módulo de hashing, o algoritmo retornará uma string de 256 bits denotando o conteúdo do bloco.

Então, é isso que dá imutabilidade ao blockchain. Como cada bloco será representado por um hash, que será calculado a partir do hash do bloco anterior, corromper qualquer bloco da cadeia fará com que os outros blocos tenham hashes inválidos, resultando na quebra de toda a rede do blockchain.

Construindo a Rede

Todo o conceito de blockchain é baseado no fato de que os blocos são “encadeados” entre si. Agora, criaremos uma classe blockchain que desempenhará a função crítica de gerenciar toda a cadeia.

Ele manterá os dados das transações e incluirá outros métodos auxiliares para completar várias funções, como adicionar novos blocos.

Vamos falar sobre os métodos auxiliares.

Adicionando o Método do Construtor

Aqui está o código:

class BlockChain(object):
    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.build_genesis()

O método do construtor init () é o que instancia o blockchain.

Aqui estão as funções de seus atributos:

self.chain - esta variável armazena todos os blocos.

self.current_data - esta variável armazena informações sobre as transações no bloco.

self.build_genesis () - este método é usado para criar o bloco inicial na cadeia.

Construindo o Bloco Genesis

O build_genesis()método é usado para criar o bloco inicial da cadeia, ou seja, um bloco sem predecessores. O bloco de gênese é o que representa o início do blockchain.

Para criá-lo, chamaremos o build_block()método e forneceremos alguns valores padrão. Os parâmetros proof_numbere previous_hashrecebem o valor zero, embora você possa fornecer qualquer valor que desejar.

Aqui está o código:

def build_genesis(self):
        self.build_block(proof_number=0, previous_hash=0)
 def build_block(self, proof_number, previous_hash):
        block = Block(
            index=len(self.chain),
            proof_number=proof_number,
            previous_hash=previous_hash,
            data=self.current_data
        )
        self.current_data = []  
        self.chain.append(block)
        return block

Confirmando a Validade do Blockchain

O confirm_validitymétodo é fundamental para examinar a integridade do blockchain e garantir que haja inconsistências.

Conforme explicado anteriormente, os hashes são essenciais para realizar a segurança do blockchain da criptomoeda, porque qualquer pequena alteração em um objeto resultará na criação de um hash totalmente diferente.

Assim, o confirm_validitymétodo utiliza uma série de declarações if para avaliar se o hash de cada bloco foi comprometido.

Além disso, ele também compara os valores de hash de cada dois blocos sucessivos para identificar quaisquer anomalias. Se a cadeia estiver funcionando corretamente, ele retorna verdadeiro; caso contrário, retorna falso.

Aqui está o código:

def confirm_validity(block, previous_block):
        if previous_block.index + 1 != block.index:
            return False
        elif previous_block.compute_hash != block.previous_hash:
            return False
        elif block.timestamp <= previous_block.timestamp:
            return False
        return True

Declaração de dados de transações

O get_datamétodo é importante para declarar os dados das transações em um bloco. Este método usa três parâmetros (informações do remetente, informações do receptor e quantidade) e adiciona os dados da transação à lista self.current_data.

Aqui está o código:

def get_data(self, sender, receiver, amount):
        self.current_data.append({
            'sender': sender,
            'receiver': receiver,
            'amount': amount
        })
        return True

Efetuando a Prova de Trabalho

Na tecnologia blockchain, Prova de Trabalho (PoW) se refere à complexidade envolvida na mineração ou geração de novos blocos no blockchain.

Por exemplo, o PoW pode ser implementado identificando um número que resolve um problema sempre que um usuário conclui algum trabalho de computação. Qualquer pessoa na rede blockchain deve achar o número complexo de identificar, mas fácil de verificar - este é o conceito principal de PoW.

Dessa forma, desestimula o spamming e compromete a integridade da rede.

Neste artigo, ilustraremos como incluir um algoritmo de Prova de Trabalho em um projeto de criptomoeda blockchain.

Finalizando com o Último Bloco

Finalmente, o método auxiliar latest_block () é usado para recuperar o último bloco na rede, que é na verdade o bloco atual.

Aqui está o código:

def latest_block(self):
        return self.chain[-1]

Implementando Blockchain Mining

Agora, esta é a seção mais emocionante!

Inicialmente, as transações são mantidas em uma lista de transações não verificadas. Mineração se refere ao processo de colocar as transações não verificadas em um bloco e resolver o problema de PoW. Pode ser referido como o trabalho de computação envolvido na verificação das transações.

Se tudo foi descoberto corretamente, um bloco é criado ou extraído e unido com os outros no blockchain. Se os usuários extraíram um bloco com sucesso, eles geralmente são recompensados ​​por usar seus recursos de computação para resolver o problema de PoW.

Aqui está o método de mineração neste projeto simples de blockchain de criptomoeda:

def block_mining(self, details_miner):
            self.get_data(
            sender="0", #it implies that this node has created a new block
            receiver=details_miner,
            quantity=1, #creating a new block (or identifying the proof number) is awarded with 1
        )
        last_block = self.latest_block
        last_proof_number = last_block.proof_number
        proof_number = self.proof_of_work(last_proof_number)
        last_hash = last_block.compute_hash
        block = self.build_block(proof_number, last_hash)
        return vars(block)

Resumo

Aqui está todo o código para nossa classe crypto blockchain em Python:

import hashlib
import time
class Block(object):
    def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
        self.index = index
        self.proof_number = proof_number
        self.previous_hash = previous_hash
        self.data = data
        self.timestamp = timestamp or time.time()
    @property
    def compute_hash(self):
        string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
        return hashlib.sha256(string_block.encode()).hexdigest()
    def __repr__(self):
        return "{} - {} - {} - {} - {}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
class BlockChain(object):
    def __init__(self):
        self.chain = []
        self.current_data = []
        self.nodes = set()
        self.build_genesis()
    def build_genesis(self):
        self.build_block(proof_number=0, previous_hash=0)
    def build_block(self, proof_number, previous_hash):
        block = Block(
            index=len(self.chain),
            proof_number=proof_number,
            previous_hash=previous_hash,
            data=self.current_data
        )
        self.current_data = []  
        self.chain.append(block)
        return block
    @staticmethod
    def confirm_validity(block, previous_block):
        if previous_block.index + 1 != block.index:
            return False
        elif previous_block.compute_hash != block.previous_hash:
            return False
        elif block.timestamp <= previous_block.timestamp:
            return False
        return True
    def get_data(self, sender, receiver, amount):
        self.current_data.append({
            'sender': sender,
            'receiver': receiver,
            'amount': amount
        })
        return True        
    @staticmethod
    def proof_of_work(last_proof):
        pass
    @property
    def latest_block(self):
        return self.chain[-1]
    def chain_validity(self):
        pass        
    def block_mining(self, details_miner):       
        self.get_data(
            sender="0", #it implies that this node has created a new block
            receiver=details_miner,
            quantity=1, #creating a new block (or identifying the proof number) is awared with 1
        )
        last_block = self.latest_block
        last_proof_number = last_block.proof_number
        proof_number = self.proof_of_work(last_proof_number)
        last_hash = last_block.compute_hash
        block = self.build_block(proof_number, last_hash)
        return vars(block)  
    def create_node(self, address):
        self.nodes.add(address)
        return True
    @staticmethod
    def get_block_object(block_data):        
        return Block(
            block_data['index'],
            block_data['proof_number'],
            block_data['previous_hash'],
            block_data['data'],
            timestamp=block_data['timestamp']
        )
blockchain = BlockChain()
print("GET READY MINING ABOUT TO START")
print(blockchain.chain)
last_block = blockchain.latest_block
last_proof_number = last_block.proof_number
proof_number = blockchain.proof_of_work(last_proof_number)
blockchain.get_data(
    sender="0", #this means that this node has constructed another block
    receiver="LiveEdu.tv", 
    amount=1, #building a new block (or figuring out the proof number) is awarded with 1
)
last_hash = last_block.compute_hash
block = blockchain.build_block(proof_number, last_hash)
print("WOW, MINING HAS BEEN SUCCESSFUL!")
print(blockchain.chain)

Agora, vamos tentar executar nosso código para ver se podemos gerar algumas moedas digitais ...

Uau, funcionou!

Conclusão

É isso!

Esperamos que este artigo tenha ajudado você a entender a tecnologia subjacente que alimenta criptomoedas como Bitcoin e Ethereum.

Acabamos de ilustrar as idéias básicas para deixar seus pés molhados na tecnologia inovadora de blockchain. O projeto acima ainda pode ser aprimorado incorporando outros recursos para torná-lo mais útil e robusto.