Elian  Harber

Elian Harber

1654612391

Go-james: James Is Your Butler & Helps You to Create, Build, Debug

go-james     

James is your butler and helps you to create, build, debug, test and run your Go projects.

When you often create new apps using Go, it quickly becomes annoying when you realize all the steps it takes to configure the basics. You need to manually create the source files, version info requires more steps to be injected into the executable, using Visual Studio Code requires you to manually setup the tasks you want to run…

Using the go-james tool, you can automate and streamline this process. The tool will take care of initializing your project, running your project, debugging it, building it and running the tests.

You should be using go-james if:

  • you're tired of setting up your projects manually
  • you don't want to have to specify the main package every time you want build or run your project
  • you keep on forgetting how to setup debugging Visual Studio Code
  • you don't want to setup your tasks file manually in Visual Studio Code
  • you want to have the Git revision, branch name and version number automatically in your project
  • you're tired of manually writing Makefiles to build, test and run your project
  • you want a better way to do tasks before and after the build than writing non-portable shell scripts
  • you want an easy way to cross-compile for all common GOOS/GOARCH combinations
  • you want a way to build, run and test your project in a cross-platform manner

Requirements

Installation

Using go get

You can run the following command to install go-james:

go get -u github.com/pieterclaerhout/go-james/cmd/go-james

This will create the go-james command in your $GOPATH/bin folder.

The tool is self-contained and doesn't have any external dependencies.

Homebrew

To install via homebrew, run the following commands:

$ brew tap pieterclaerhout/go-james
==> Tapping pieterclaerhout/go-james
Cloning into '/usr/local/Homebrew/Library/Taps/pieterclaerhout/homebrew-go-james'...
remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (4/4), done.
remote: Total 4 (delta 0), reused 4 (delta 0), pack-reused 0
Receiving objects: 100% (4/4), done.
Tapped 1 formula (27 files, 26.5KB).

$ brew install go-james
==> Installing go-james from pieterclaerhout/go-james
==> Downloading https://github.com/pieterclaerhout/go-james/releases/download/v1.6.0/go-james_darwin_amd64.tar.gz
######################################################################## 100.0%
🍺  /usr/local/Cellar/go-james/1.6.0: 4 files, 11.5MB, built in 3 seconds

Manually

To install it manually, download the go-james executable from the releases and place it in $GOPATH/bin.

Starting a new project

To start a new project, you can use the new subcommand as follows:

go-james new --path=<target path> \
             --package=<package> \
             --name=<name of your project> \
             --description=<description of your project> \
             --copyright=<copyright of your project> \
             [--with-git] \
             [--with-docker] \
             [--with-github-action] \
             [--with-gitlab-ci] \
             [--overwrite]

When you run it, you'll get the following output:

➜ go-james new --path go-example --package github.com/pieterclaerhout/go-example
Creating package: github.com/pieterclaerhout/go-example
Project path: /Users/pclaerhout/Desktop/go-example
Writing: go-example
Writing: go-example/go-james.json
Writing: go-example/.vscode
Writing: go-example/.vscode/tasks.json
Writing: go-example/.vscode/settings.json
Writing: go-example/.vscode/launch.json
Writing: go-example/LICENSE
Writing: go-example/.gitignore
Writing: go-example/.dockerignore
Writing: go-example/Dockerfile
Writing: go-example/README.md
Writing: go-example/scripts/post_build
Writing: go-example/scripts/post_build/post_build.example.go
Writing: go-example/library.go
Writing: go-example/library_test.go
Writing: go-example/cmd/go-example
Writing: go-example/cmd/go-example/main.go
Writing: go-example/versioninfo
Writing: go-example/versioninfo/versioninfo.go
Writing: go-example/scripts/pre_build
Writing: go-example/scripts/pre_build/pre_build.example.go
Writing: go-example/go.mod

It will automatically create the following folder and file structure:

go-example
.
├── Dockerfile
├── Downloads
├── DropBox
├── Twixl\ Publisher
└── go-example
    ├── Dockerfile
    ├── LICENSE
    ├── README.md
    ├── cmd
    │   └── go-example
    │       └── main.go
    ├── go-james.json
    ├── go.mod
    ├── library.go
    ├── library_test.go
    ├── scripts
    │   ├── post_build
    │   │   └── post_build.example.go
    │   └── pre_build
    │       └── pre_build.example.go
    └── versioninfo
        └── versioninfo.go

An important file which is generated and can be used to further customize the project and it's settings is the go-james.json file which sits next to the go.mod file.

You can specify the following options:

  • --path: the path where the new project should be created, e.g. /home/username/go-example (if not specified, it will create a directory with the name of the prject in the current path)
  • --package: the main package for the new project, e.g. github.com/pieterclaerhout/go-example (defaults to the project name if specified)
  • --name: the name of the project, if not specified, the last part of the path is used
  • --description: the description of the project, used for the readme
  • --copyright: the copyright of the project, used for the readme
  • --with-git: if specified, a local Git repository will be created for the project and the source files will automatically be committed.
  • --with-docker: if specified, a sample Dockerfile and .dockerignore file will be created.
  • --with-github-action: if specified, a sample Github Actions file will be created.
  • --with-gitlab-ci: if specified, a sample Gitlab-CI file will be created.
  • --overwrite: if the destination path already exists, overwrite it (be careful, the original folder will be replaced)

Initializing an existing project

When you already have an existing folder structure, you can run the init command to add the missing pieces.

go-james init

This command is supposed to run from the project's directory and doesn't take any arguments.

Building a project

From within the project root, run the build command to build the executable:

go-james build [-v] [--output=<path>] [--goos=<os>] [--goarch=<arch>]

By default, the output is put in the build subdirectory but can be customized in the configuration file.

You can specify the following options:

  • -v: the packages which are built will be listed.
  • --output: you can override the default output path as specified in the configuration file.
  • --goos: you can override the GOOS environment variable which indicates for which OS you are compiling.
  • --goarch: you can override the GOARCH environment variable which indicates for which architecture you are compiling.

You can read more about the GOOS and GOARCH environment variables here.

As part of the build process, the versioninfo package will be filled with the following details:

With every build, these variables are automatically updated.

Pre-build and post-build hooks

Just before the build, if a file called <project_root>/scripts/pre_build/pre_build.go is present, it will be executed and will get a lot of info about the build injected. It's a plain Go file, so use whatever trick or tool you know. A sample pre-build script looks as follows:

package main

import (
    "github.com/pieterclaerhout/go-james"
    "github.com/pieterclaerhout/go-log"
)

func main() {

    args, err := james.ParseBuildArgs()
    log.CheckError(err)

    log.InfoDump(args, "pre_build arguments")

}

You can also execute a script after the build. To do so, create a file <project_root>/scripts/post_build/post_build.go with contents similar to:

package main

import (
    "github.com/pieterclaerhout/go-james"
    "github.com/pieterclaerhout/go-log"
)

func main() {

    args, err := james.ParseBuildArgs()
    log.CheckError(err)

    log.InfoDump(args, "post_build arguments")

}

Parsing arguments in pre/post build scripts.

To parse the arguments, you can use james.ParseBuildArgs().

The parameters it gets are are struct of the type james.BuildArgs:

james.BuildArgs{
  ProjectPath: "/home/user/go-james",
  OutputPath: "/home/user/go-james/build/go-james",
  GOOS: "darwin",
  GOARCH: "amd64",
  ProjectName: "go-james",
  ProjectDescription: "James is your butler and helps you to create, build, test and run your Go projects",
  ProjectCopyright: "© 2019-2020 Copyright Pieter Claerhout",
  Version: "0.7.0",
  Revision: "2065b13",
  Branch: "master",
  RawBuildCommand: []string{
    "go",
    "build",
    "-o",
    "build/go-james",
    "-ldflags",
    "-s -w -X github.com/pieterclaerhout/go-james/versioninfo.ProjectName=go-james -X 'github.com/pieterclaerhout/go-james/versioninfo.ProjectDescription=James is your butler and helps you to create, build, test and run your Go projects' -X 'github.com/pieterclaerhout/go-james/versioninfo.ProjectCopyright=© 2019 Copyright Pieter Claerhout' -X github.com/pieterclaerhout/go-james/versioninfo.Version=0.7.0 -X github.com/pieterclaerhout/go-james/versioninfo.Revision=2065b13 -X github.com/pieterclaerhout/go-james/versioninfo.Branch=master",
    "-trimpath",
    "github.com/pieterclaerhout/go-james/cmd/go-james",
  },
}

The same information is also available in the following environment variables:

GO_JAMES_BRANCH="master"
GO_JAMES_GOARCH="amd64"
GO_JAMES_GOOS="darwin"
GO_JAMES_OUTPUT_PATH="/home/user/go-james/build/go-james"
GO_JAMES_PROJECT_COPYRIGHT="© 2019-2020 Copyright Pieter Claerhout"
GO_JAMES_PROJECT_DESCRIPTION="James is your butler and helps you to create, build, test and run your Go projects"
GO_JAMES_PROJECT_NAME="go-james"
GO_JAMES_PROJECT_PATH="/home/user/go-james"
GO_JAMES_REVISION="2065b13"
GO_JAMES_VERSION="0.7.0"

Using Bash scripts for pre/post build actions.

If you prefer to use a bash script instead for the pre/post build actions, you can create a file called:

<project_root>/scripts/post_build/pre_build.sh

or

<project_root>/scripts/post_build/post_build.sh

It should be marked as executable.

Using Batch files for pre/post build actions.

If you prefer to use a batch file on Windows instead for the pre/post build actions, you can create a file called:

<project_root>/scripts/post_build/pre_build.bat

or

<project_root>/scripts/post_build/post_build.bat

How go-james defines which pre/post build script to run

go-james will search for pre/post build scripts in the following order:

  • pre_build.go / post_build.go
  • pre_build.sh / post_build.sh
  • pre_build.bat / post_build.bat

Packaging a project

From within the project root, run the package command to build the executable for windows / darwin / linux in the 386 and amd64 variants and compresses the result as a .zip (windows) or .tgz (linux / mac):

go-james package [-v] [--concurrency=4]

By default, the output is put in the build subdirectory but can be customized in the configuration file.

The filenames which are constructed use the following convention:

build/<project.name>_<goos>-<goarch>_v<project.version>.[zip,tgz]

The executable will be compressed and, if present in the project, the project's README.md file as well.

You can specify the following options:

  • -v: the packages which are built will be listed.
  • --concurrency: how many package processes should run in parallel, defaults to the number of CPUs.

As part of the build process, the versioninfo package will be filled with the following details:

  • versioninfo.ProjectName: the name of the project from the configuration file
  • versioninfo.ProjectDescription: the description of the project from the configuration file
  • versioninfo.Version: the version of the project from the configuration file
  • versioninfo.Revision: the current Git commit hash
  • versioninfo.Branch: the current Git branch name

With every build, these variables are automatically updated.

Debugging a project

From within the project root, run:

go-james debug

This will build the project and run it's main target through the Delve debugger. If the dlv command is not yet present in your $GOPATH/bin folder, it will automaticall be installed the first time you run it.

When creating a new project or performing init on an existing project, it also configures debugging from within Visual Studio Code. It's a simple as setting one or more breakpoints and choose "Start" > "Debug" from the menu. It creates a launch configuration called Debug.

Running a project

From within the project root, run:

go-james run <args>

This will build the project and run it's main target passing the <args> to the command.

Testing a project

From within the project root, run:

go-james test

This will run all the tests defined in the package.

Installing the executable

To install the main executable of your project in $GOPATH/bin, simply run the install command.

This will build the project and install it in the $GOPATH/bin folder. The name of the executable is the basename of build output path (as specified in the configuration file.

go-james uninstall

Uninstalling the executable

Similar to the install command, there is also an uninstall command which removes the executable from $GOPATH/bin.

go-james uninstall

Running a static analysis

You can use the staticcheck command to run the staticcheck static analyzer. The binary required to run staticcheck is automatically installed if needed.

go-james staticcheck

Building a Docker image

You can use the docker-image command to build a Docker image using the Dockerfile in the project folder. When you create a new project, a starter Dockerfile will be created automatically.

go-james docker-container

The config file go-james.json

When you create a new project or init an existing one, a go-james.json file will be created in the root of your project. This file can be used to configure the project. The full config file is as follows:

{
    "project": {
        "name": "go-example",
        "version": "1.0.0",
        "description": "",
        "copyright": "",
        "package": "github.com/pieterclaerhout/go-example",
        "main_package": "github.com/pieterclaerhout/go-example/cmd/go-example"
    },
    "build": {
        "output_path": "build/go-example",
        "ld_flags": [
            "-s",
            "-w"
        ],
        "ld_flags_windows": [
            "-s",
            "-w",
            "-H",
            "windowsgui"
        ],
        "ld_flags_darwin": [],
        "ld_flags_linux": [],
        "extra_args": [
            "-trimpath"
        ],
        "use_gotip": false
    },
    "run": {
        "environ": {
            "var": "val"
        }
    },
    "package": {
        "include_readme": true
    },
    "test": {
        "extra_args": []
    },
    "staticcheck": {
        "checks": ["all", "-ST1005", "-ST1000"]
    },
    "docker-image": {
        "name": "go-james",
        "repository": "pieterclaerhout/go-james",
        "tag": "revision",
        "prune_images_after_build": false
    }
}

Project Config

  • name: the name of your project (will be availabme under <package>/versioninfo.ProjectName)
  • version: the version of your project (will be availabme under <package>/versioninfo.Version)
  • description: the description of your project (will be availabme under <package>/versioninfo.ProjectDescription)
  • copyright: the description of your project (will be availabme under <package>/versioninfo.ProjectCopyright)
  • package: the root package of your project
  • main_package: the full path to the main package of your app, defaults to <package>/cmd/<project-name>

Build Config

  • output_path: the path where the built executable should be placed. Defaults to build/<project-name>
  • ld_flags: the linker flags you want to use for building. You can find more info about these flags here. These are only used if you don't specify specific parameters for a specifc GOOS.
  • ld_flags_darwin: the linker flags you want to use for building darwin. You can find more info about these flags here.
  • ld_flags_linux: the linker flags you want to use for building for linux. You can find more info about these flags here.
  • ld_flags_windows: the linker flags you want to use for building for windows. You can find more info about these flags here.
  • extra_args: contains any extra command-line parameters you want to add to the go build command when you run go-james build.
  • use_gotip: setting this to true uses gotip to compile instead of the regular gocommand. Make sure you have gotip installed.

Run Config

  • environ: the environment variables to use when running the app

Package Config

  • include_readme: boolean indicating if the README.md file should be included in the package or not

Test Config

  • extra_args: contains any extra command-line parameters you want to add to the go test command when you run go-james test.

Staticcheck Config

Docker Image Config

  • name: the name of the docker image you want to create. Defaults to the project name.
  • repository: the repository to which you want to push the image. If left empty, the image will only be created locally.
  • tag: can be either revision or version (the default) and indicates what value should be used for the tag.
  • prune_images_after_build: if set to true, a docker image prune -f will be executed after the docker build step.

Bootstrapping go-james

If you want to build go-james from scratch, you can use the following command (or use the "bootstrap" build task in Visual Studio Code):

go build -v -o build/go-james github.com/pieterclaerhout/go-james/cmd/go-james

If you have a version of go-james installed, you can use it to build itself.

Roadmap

To get an idea on what's coming, you can check the GitHub Milestones.

Resources

Follow my weblog about Go & Kubernetes :-)

Author: Pieterclaerhout
Source Code: https://github.com/pieterclaerhout/go-james 
License: Apache-2.0 license

#go #golang #testing #debugging 

What is GEEK

Buddha Community

Go-james: James Is Your Butler & Helps You to Create, Build, Debug
Easter  Deckow

Easter Deckow

1655630160

PyTumblr: A Python Tumblr API v2 Client

PyTumblr

Installation

Install via pip:

$ pip install pytumblr

Install from source:

$ git clone https://github.com/tumblr/pytumblr.git
$ cd pytumblr
$ python setup.py install

Usage

Create a client

A pytumblr.TumblrRestClient is the object you'll make all of your calls to the Tumblr API through. Creating one is this easy:

client = pytumblr.TumblrRestClient(
    '<consumer_key>',
    '<consumer_secret>',
    '<oauth_token>',
    '<oauth_secret>',
)

client.info() # Grabs the current user information

Two easy ways to get your credentials to are:

  1. The built-in interactive_console.py tool (if you already have a consumer key & secret)
  2. The Tumblr API console at https://api.tumblr.com/console
  3. Get sample login code at https://api.tumblr.com/console/calls/user/info

Supported Methods

User Methods

client.info() # get information about the authenticating user
client.dashboard() # get the dashboard for the authenticating user
client.likes() # get the likes for the authenticating user
client.following() # get the blogs followed by the authenticating user

client.follow('codingjester.tumblr.com') # follow a blog
client.unfollow('codingjester.tumblr.com') # unfollow a blog

client.like(id, reblogkey) # like a post
client.unlike(id, reblogkey) # unlike a post

Blog Methods

client.blog_info(blogName) # get information about a blog
client.posts(blogName, **params) # get posts for a blog
client.avatar(blogName) # get the avatar for a blog
client.blog_likes(blogName) # get the likes on a blog
client.followers(blogName) # get the followers of a blog
client.blog_following(blogName) # get the publicly exposed blogs that [blogName] follows
client.queue(blogName) # get the queue for a given blog
client.submission(blogName) # get the submissions for a given blog

Post Methods

Creating posts

PyTumblr lets you create all of the various types that Tumblr supports. When using these types there are a few defaults that are able to be used with any post type.

The default supported types are described below.

  • state - a string, the state of the post. Supported types are published, draft, queue, private
  • tags - a list, a list of strings that you want tagged on the post. eg: ["testing", "magic", "1"]
  • tweet - a string, the string of the customized tweet you want. eg: "Man I love my mega awesome post!"
  • date - a string, the customized GMT that you want
  • format - a string, the format that your post is in. Support types are html or markdown
  • slug - a string, the slug for the url of the post you want

We'll show examples throughout of these default examples while showcasing all the specific post types.

Creating a photo post

Creating a photo post supports a bunch of different options plus the described default options * caption - a string, the user supplied caption * link - a string, the "click-through" url for the photo * source - a string, the url for the photo you want to use (use this or the data parameter) * data - a list or string, a list of filepaths or a single file path for multipart file upload

#Creates a photo post using a source URL
client.create_photo(blogName, state="published", tags=["testing", "ok"],
                    source="https://68.media.tumblr.com/b965fbb2e501610a29d80ffb6fb3e1ad/tumblr_n55vdeTse11rn1906o1_500.jpg")

#Creates a photo post using a local filepath
client.create_photo(blogName, state="queue", tags=["testing", "ok"],
                    tweet="Woah this is an incredible sweet post [URL]",
                    data="/Users/johnb/path/to/my/image.jpg")

#Creates a photoset post using several local filepaths
client.create_photo(blogName, state="draft", tags=["jb is cool"], format="markdown",
                    data=["/Users/johnb/path/to/my/image.jpg", "/Users/johnb/Pictures/kittens.jpg"],
                    caption="## Mega sweet kittens")

Creating a text post

Creating a text post supports the same options as default and just a two other parameters * title - a string, the optional title for the post. Supports markdown or html * body - a string, the body of the of the post. Supports markdown or html

#Creating a text post
client.create_text(blogName, state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")

Creating a quote post

Creating a quote post supports the same options as default and two other parameter * quote - a string, the full text of the qote. Supports markdown or html * source - a string, the cited source. HTML supported

#Creating a quote post
client.create_quote(blogName, state="queue", quote="I am the Walrus", source="Ringo")

Creating a link post

  • title - a string, the title of post that you want. Supports HTML entities.
  • url - a string, the url that you want to create a link post for.
  • description - a string, the desciption of the link that you have
#Create a link post
client.create_link(blogName, title="I like to search things, you should too.", url="https://duckduckgo.com",
                   description="Search is pretty cool when a duck does it.")

Creating a chat post

Creating a chat post supports the same options as default and two other parameters * title - a string, the title of the chat post * conversation - a string, the text of the conversation/chat, with diablog labels (no html)

#Create a chat post
chat = """John: Testing can be fun!
Renee: Testing is tedious and so are you.
John: Aw.
"""
client.create_chat(blogName, title="Renee just doesn't understand.", conversation=chat, tags=["renee", "testing"])

Creating an audio post

Creating an audio post allows for all default options and a has 3 other parameters. The only thing to keep in mind while dealing with audio posts is to make sure that you use the external_url parameter or data. You cannot use both at the same time. * caption - a string, the caption for your post * external_url - a string, the url of the site that hosts the audio file * data - a string, the filepath of the audio file you want to upload to Tumblr

#Creating an audio file
client.create_audio(blogName, caption="Rock out.", data="/Users/johnb/Music/my/new/sweet/album.mp3")

#lets use soundcloud!
client.create_audio(blogName, caption="Mega rock out.", external_url="https://soundcloud.com/skrillex/sets/recess")

Creating a video post

Creating a video post allows for all default options and has three other options. Like the other post types, it has some restrictions. You cannot use the embed and data parameters at the same time. * caption - a string, the caption for your post * embed - a string, the HTML embed code for the video * data - a string, the path of the file you want to upload

#Creating an upload from YouTube
client.create_video(blogName, caption="Jon Snow. Mega ridiculous sword.",
                    embed="http://www.youtube.com/watch?v=40pUYLacrj4")

#Creating a video post from local file
client.create_video(blogName, caption="testing", data="/Users/johnb/testing/ok/blah.mov")

Editing a post

Updating a post requires you knowing what type a post you're updating. You'll be able to supply to the post any of the options given above for updates.

client.edit_post(blogName, id=post_id, type="text", title="Updated")
client.edit_post(blogName, id=post_id, type="photo", data="/Users/johnb/mega/awesome.jpg")

Reblogging a Post

Reblogging a post just requires knowing the post id and the reblog key, which is supplied in the JSON of any post object.

client.reblog(blogName, id=125356, reblog_key="reblog_key")

Deleting a post

Deleting just requires that you own the post and have the post id

client.delete_post(blogName, 123456) # Deletes your post :(

A note on tags: When passing tags, as params, please pass them as a list (not a comma-separated string):

client.create_text(blogName, tags=['hello', 'world'], ...)

Getting notes for a post

In order to get the notes for a post, you need to have the post id and the blog that it is on.

data = client.notes(blogName, id='123456')

The results include a timestamp you can use to make future calls.

data = client.notes(blogName, id='123456', before_timestamp=data["_links"]["next"]["query_params"]["before_timestamp"])

Tagged Methods

# get posts with a given tag
client.tagged(tag, **params)

Using the interactive console

This client comes with a nice interactive console to run you through the OAuth process, grab your tokens (and store them for future use).

You'll need pyyaml installed to run it, but then it's just:

$ python interactive-console.py

and away you go! Tokens are stored in ~/.tumblr and are also shared by other Tumblr API clients like the Ruby client.

Running tests

The tests (and coverage reports) are run with nose, like this:

python setup.py test

Author: tumblr
Source Code: https://github.com/tumblr/pytumblr
License: Apache-2.0 license

#python #api 

Tamale  Moses

Tamale Moses

1669003576

Exploring Mutable and Immutable in Python

In this Python article, let's learn about Mutable and Immutable in Python. 

Mutable and Immutable in Python

Mutable is a fancy way of saying that the internal state of the object is changed/mutated. So, the simplest definition is: An object whose internal state can be changed is mutable. On the other hand, immutable doesn’t allow any change in the object once it has been created.

Both of these states are integral to Python data structure. If you want to become more knowledgeable in the entire Python Data Structure, take this free course which covers multiple data structures in Python including tuple data structure which is immutable. You will also receive a certificate on completion which is sure to add value to your portfolio.

Mutable Definition

Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’ is the ability of objects to change their values. These are often the objects that store a collection of data.

Immutable Definition

Immutable is the when no change is possible over time. In Python, if the value of an object cannot be changed over time, then it is known as immutable. Once created, the value of these objects is permanent.

List of Mutable and Immutable objects

Objects of built-in type that are mutable are:

  • Lists
  • Sets
  • Dictionaries
  • User-Defined Classes (It purely depends upon the user to define the characteristics) 

Objects of built-in type that are immutable are:

  • Numbers (Integer, Rational, Float, Decimal, Complex & Booleans)
  • Strings
  • Tuples
  • Frozen Sets
  • User-Defined Classes (It purely depends upon the user to define the characteristics)

Object mutability is one of the characteristics that makes Python a dynamically typed language. Though Mutable and Immutable in Python is a very basic concept, it can at times be a little confusing due to the intransitive nature of immutability.

Objects in Python

In Python, everything is treated as an object. Every object has these three attributes:

  • Identity – This refers to the address that the object refers to in the computer’s memory.
  • Type – This refers to the kind of object that is created. For example- integer, list, string etc. 
  • Value – This refers to the value stored by the object. For example – List=[1,2,3] would hold the numbers 1,2 and 3

While ID and Type cannot be changed once it’s created, values can be changed for Mutable objects.

Check out this free python certificate course to get started with Python.

Mutable Objects in Python

I believe, rather than diving deep into the theory aspects of mutable and immutable in Python, a simple code would be the best way to depict what it means in Python. Hence, let us discuss the below code step-by-step:

#Creating a list which contains name of Indian cities  

cities = [‘Delhi’, ‘Mumbai’, ‘Kolkata’]

# Printing the elements from the list cities, separated by a comma & space

for city in cities:
		print(city, end=’, ’)

Output [1]: Delhi, Mumbai, Kolkata

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(cities)))

Output [2]: 0x1691d7de8c8

#Adding a new city to the list cities

cities.append(‘Chennai’)

#Printing the elements from the list cities, separated by a comma & space 

for city in cities:
	print(city, end=’, ’)

Output [3]: Delhi, Mumbai, Kolkata, Chennai

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(cities)))

Output [4]: 0x1691d7de8c8

The above example shows us that we were able to change the internal state of the object ‘cities’ by adding one more city ‘Chennai’ to it, yet, the memory address of the object did not change. This confirms that we did not create a new object, rather, the same object was changed or mutated. Hence, we can say that the object which is a type of list with reference variable name ‘cities’ is a MUTABLE OBJECT.

Let us now discuss the term IMMUTABLE. Considering that we understood what mutable stands for, it is obvious that the definition of immutable will have ‘NOT’ included in it. Here is the simplest definition of immutable– An object whose internal state can NOT be changed is IMMUTABLE.

Again, if you try and concentrate on different error messages, you have encountered, thrown by the respective IDE; you use you would be able to identify the immutable objects in Python. For instance, consider the below code & associated error message with it, while trying to change the value of a Tuple at index 0. 

#Creating a Tuple with variable name ‘foo’

foo = (1, 2)

#Changing the index[0] value from 1 to 3

foo[0] = 3
	
TypeError: 'tuple' object does not support item assignment 

Immutable Objects in Python

Once again, a simple code would be the best way to depict what immutable stands for. Hence, let us discuss the below code step-by-step:

#Creating a Tuple which contains English name of weekdays

weekdays = ‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’

# Printing the elements of tuple weekdays

print(weekdays)

Output [1]:  (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’)

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(weekdays)))

Output [2]: 0x1691cc35090

#tuples are immutable, so you cannot add new elements, hence, using merge of tuples with the # + operator to add a new imaginary day in the tuple ‘weekdays’

weekdays  +=  ‘Pythonday’,

#Printing the elements of tuple weekdays

print(weekdays)

Output [3]: (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’, ‘Pythonday’)

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(weekdays)))

Output [4]: 0x1691cc8ad68

This above example shows that we were able to use the same variable name that is referencing an object which is a type of tuple with seven elements in it. However, the ID or the memory location of the old & new tuple is not the same. We were not able to change the internal state of the object ‘weekdays’. The Python program manager created a new object in the memory address and the variable name ‘weekdays’ started referencing the new object with eight elements in it.  Hence, we can say that the object which is a type of tuple with reference variable name ‘weekdays’ is an IMMUTABLE OBJECT.

Also Read: Understanding the Exploratory Data Analysis (EDA) in Python

Where can you use mutable and immutable objects:

Mutable objects can be used where you want to allow for any updates. For example, you have a list of employee names in your organizations, and that needs to be updated every time a new member is hired. You can create a mutable list, and it can be updated easily.

Immutability offers a lot of useful applications to different sensitive tasks we do in a network centred environment where we allow for parallel processing. By creating immutable objects, you seal the values and ensure that no threads can invoke overwrite/update to your data. This is also useful in situations where you would like to write a piece of code that cannot be modified. For example, a debug code that attempts to find the value of an immutable object.

Watch outs:  Non transitive nature of Immutability:

OK! Now we do understand what mutable & immutable objects in Python are. Let’s go ahead and discuss the combination of these two and explore the possibilities. Let’s discuss, as to how will it behave if you have an immutable object which contains the mutable object(s)? Or vice versa? Let us again use a code to understand this behaviour–

#creating a tuple (immutable object) which contains 2 lists(mutable) as it’s elements

#The elements (lists) contains the name, age & gender 

person = (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the tuple

print(person)

Output [1]: (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(person)))

Output [2]: 0x1691ef47f88

#Changing the age for the 1st element. Selecting 1st element of tuple by using indexing [0] then 2nd element of the list by using indexing [1] and assigning a new value for age as 4

person[0][1] = 4

#printing the updated tuple

print(person)

Output [3]: (['Ayaan', 4, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(person)))

Output [4]: 0x1691ef47f88

In the above code, you can see that the object ‘person’ is immutable since it is a type of tuple. However, it has two lists as it’s elements, and we can change the state of lists (lists being mutable). So, here we did not change the object reference inside the Tuple, but the referenced object was mutated.

Also Read: Real-Time Object Detection Using TensorFlow

Same way, let’s explore how it will behave if you have a mutable object which contains an immutable object? Let us again use a code to understand the behaviour–

#creating a list (mutable object) which contains tuples(immutable) as it’s elements

list1 = [(1, 2, 3), (4, 5, 6)]

#printing the list

print(list1)

Output [1]: [(1, 2, 3), (4, 5, 6)]

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(list1)))

Output [2]: 0x1691d5b13c8	

#changing object reference at index 0

list1[0] = (7, 8, 9)

#printing the list

Output [3]: [(7, 8, 9), (4, 5, 6)]

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(list1)))

Output [4]: 0x1691d5b13c8

As an individual, it completely depends upon you and your requirements as to what kind of data structure you would like to create with a combination of mutable & immutable objects. I hope that this information will help you while deciding the type of object you would like to select going forward.

Before I end our discussion on IMMUTABILITY, allow me to use the word ‘CAVITE’ when we discuss the String and Integers. There is an exception, and you may see some surprising results while checking the truthiness for immutability. For instance:
#creating an object of integer type with value 10 and reference variable name ‘x’ 

x = 10
 

#printing the value of ‘x’

print(x)

Output [1]: 10

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(x)))

Output [2]: 0x538fb560

#creating an object of integer type with value 10 and reference variable name ‘y’

y = 10

#printing the value of ‘y’

print(y)

Output [3]: 10

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(y)))

Output [4]: 0x538fb560

As per our discussion and understanding, so far, the memory address for x & y should have been different, since, 10 is an instance of Integer class which is immutable. However, as shown in the above code, it has the same memory address. This is not something that we expected. It seems that what we have understood and discussed, has an exception as well.

Quick checkPython Data Structures

Immutability of Tuple

Tuples are immutable and hence cannot have any changes in them once they are created in Python. This is because they support the same sequence operations as strings. We all know that strings are immutable. The index operator will select an element from a tuple just like in a string. Hence, they are immutable.

Exceptions in immutability

Like all, there are exceptions in the immutability in python too. Not all immutable objects are really mutable. This will lead to a lot of doubts in your mind. Let us just take an example to understand this.

Consider a tuple ‘tup’.

Now, if we consider tuple tup = (‘GreatLearning’,[4,3,1,2]) ;

We see that the tuple has elements of different data types. The first element here is a string which as we all know is immutable in nature. The second element is a list which we all know is mutable. Now, we all know that the tuple itself is an immutable data type. It cannot change its contents. But, the list inside it can change its contents. So, the value of the Immutable objects cannot be changed but its constituent objects can. change its value.

FAQs

1. Difference between mutable vs immutable in Python?

Mutable ObjectImmutable Object
State of the object can be modified after it is created.State of the object can’t be modified once it is created.
They are not thread safe.They are thread safe
Mutable classes are not final.It is important to make the class final before creating an immutable object.

2. What are the mutable and immutable data types in Python?

  • Some mutable data types in Python are:

list, dictionary, set, user-defined classes.

  • Some immutable data types are: 

int, float, decimal, bool, string, tuple, range.

3. Are lists mutable in Python?

Lists in Python are mutable data types as the elements of the list can be modified, individual elements can be replaced, and the order of elements can be changed even after the list has been created.
(Examples related to lists have been discussed earlier in this blog.)

4. Why are tuples called immutable types?

Tuple and list data structures are very similar, but one big difference between the data types is that lists are mutable, whereas tuples are immutable. The reason for the tuple’s immutability is that once the elements are added to the tuple and the tuple has been created; it remains unchanged.

A programmer would always prefer building a code that can be reused instead of making the whole data object again. Still, even though tuples are immutable, like lists, they can contain any Python object, including mutable objects.

5. Are sets mutable in Python?

A set is an iterable unordered collection of data type which can be used to perform mathematical operations (like union, intersection, difference etc.). Every element in a set is unique and immutable, i.e. no duplicate values should be there, and the values can’t be changed. However, we can add or remove items from the set as the set itself is mutable.

6. Are strings mutable in Python?

Strings are not mutable in Python. Strings are a immutable data types which means that its value cannot be updated.

Join Great Learning Academy’s free online courses and upgrade your skills today.


Original article source at: https://www.mygreatlearning.com

#python 

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

Elian  Harber

Elian Harber

1654612391

Go-james: James Is Your Butler & Helps You to Create, Build, Debug

go-james     

James is your butler and helps you to create, build, debug, test and run your Go projects.

When you often create new apps using Go, it quickly becomes annoying when you realize all the steps it takes to configure the basics. You need to manually create the source files, version info requires more steps to be injected into the executable, using Visual Studio Code requires you to manually setup the tasks you want to run…

Using the go-james tool, you can automate and streamline this process. The tool will take care of initializing your project, running your project, debugging it, building it and running the tests.

You should be using go-james if:

  • you're tired of setting up your projects manually
  • you don't want to have to specify the main package every time you want build or run your project
  • you keep on forgetting how to setup debugging Visual Studio Code
  • you don't want to setup your tasks file manually in Visual Studio Code
  • you want to have the Git revision, branch name and version number automatically in your project
  • you're tired of manually writing Makefiles to build, test and run your project
  • you want a better way to do tasks before and after the build than writing non-portable shell scripts
  • you want an easy way to cross-compile for all common GOOS/GOARCH combinations
  • you want a way to build, run and test your project in a cross-platform manner

Requirements

Installation

Using go get

You can run the following command to install go-james:

go get -u github.com/pieterclaerhout/go-james/cmd/go-james

This will create the go-james command in your $GOPATH/bin folder.

The tool is self-contained and doesn't have any external dependencies.

Homebrew

To install via homebrew, run the following commands:

$ brew tap pieterclaerhout/go-james
==> Tapping pieterclaerhout/go-james
Cloning into '/usr/local/Homebrew/Library/Taps/pieterclaerhout/homebrew-go-james'...
remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (4/4), done.
remote: Total 4 (delta 0), reused 4 (delta 0), pack-reused 0
Receiving objects: 100% (4/4), done.
Tapped 1 formula (27 files, 26.5KB).

$ brew install go-james
==> Installing go-james from pieterclaerhout/go-james
==> Downloading https://github.com/pieterclaerhout/go-james/releases/download/v1.6.0/go-james_darwin_amd64.tar.gz
######################################################################## 100.0%
🍺  /usr/local/Cellar/go-james/1.6.0: 4 files, 11.5MB, built in 3 seconds

Manually

To install it manually, download the go-james executable from the releases and place it in $GOPATH/bin.

Starting a new project

To start a new project, you can use the new subcommand as follows:

go-james new --path=<target path> \
             --package=<package> \
             --name=<name of your project> \
             --description=<description of your project> \
             --copyright=<copyright of your project> \
             [--with-git] \
             [--with-docker] \
             [--with-github-action] \
             [--with-gitlab-ci] \
             [--overwrite]

When you run it, you'll get the following output:

➜ go-james new --path go-example --package github.com/pieterclaerhout/go-example
Creating package: github.com/pieterclaerhout/go-example
Project path: /Users/pclaerhout/Desktop/go-example
Writing: go-example
Writing: go-example/go-james.json
Writing: go-example/.vscode
Writing: go-example/.vscode/tasks.json
Writing: go-example/.vscode/settings.json
Writing: go-example/.vscode/launch.json
Writing: go-example/LICENSE
Writing: go-example/.gitignore
Writing: go-example/.dockerignore
Writing: go-example/Dockerfile
Writing: go-example/README.md
Writing: go-example/scripts/post_build
Writing: go-example/scripts/post_build/post_build.example.go
Writing: go-example/library.go
Writing: go-example/library_test.go
Writing: go-example/cmd/go-example
Writing: go-example/cmd/go-example/main.go
Writing: go-example/versioninfo
Writing: go-example/versioninfo/versioninfo.go
Writing: go-example/scripts/pre_build
Writing: go-example/scripts/pre_build/pre_build.example.go
Writing: go-example/go.mod

It will automatically create the following folder and file structure:

go-example
.
├── Dockerfile
├── Downloads
├── DropBox
├── Twixl\ Publisher
└── go-example
    ├── Dockerfile
    ├── LICENSE
    ├── README.md
    ├── cmd
    │   └── go-example
    │       └── main.go
    ├── go-james.json
    ├── go.mod
    ├── library.go
    ├── library_test.go
    ├── scripts
    │   ├── post_build
    │   │   └── post_build.example.go
    │   └── pre_build
    │       └── pre_build.example.go
    └── versioninfo
        └── versioninfo.go

An important file which is generated and can be used to further customize the project and it's settings is the go-james.json file which sits next to the go.mod file.

You can specify the following options:

  • --path: the path where the new project should be created, e.g. /home/username/go-example (if not specified, it will create a directory with the name of the prject in the current path)
  • --package: the main package for the new project, e.g. github.com/pieterclaerhout/go-example (defaults to the project name if specified)
  • --name: the name of the project, if not specified, the last part of the path is used
  • --description: the description of the project, used for the readme
  • --copyright: the copyright of the project, used for the readme
  • --with-git: if specified, a local Git repository will be created for the project and the source files will automatically be committed.
  • --with-docker: if specified, a sample Dockerfile and .dockerignore file will be created.
  • --with-github-action: if specified, a sample Github Actions file will be created.
  • --with-gitlab-ci: if specified, a sample Gitlab-CI file will be created.
  • --overwrite: if the destination path already exists, overwrite it (be careful, the original folder will be replaced)

Initializing an existing project

When you already have an existing folder structure, you can run the init command to add the missing pieces.

go-james init

This command is supposed to run from the project's directory and doesn't take any arguments.

Building a project

From within the project root, run the build command to build the executable:

go-james build [-v] [--output=<path>] [--goos=<os>] [--goarch=<arch>]

By default, the output is put in the build subdirectory but can be customized in the configuration file.

You can specify the following options:

  • -v: the packages which are built will be listed.
  • --output: you can override the default output path as specified in the configuration file.
  • --goos: you can override the GOOS environment variable which indicates for which OS you are compiling.
  • --goarch: you can override the GOARCH environment variable which indicates for which architecture you are compiling.

You can read more about the GOOS and GOARCH environment variables here.

As part of the build process, the versioninfo package will be filled with the following details:

With every build, these variables are automatically updated.

Pre-build and post-build hooks

Just before the build, if a file called <project_root>/scripts/pre_build/pre_build.go is present, it will be executed and will get a lot of info about the build injected. It's a plain Go file, so use whatever trick or tool you know. A sample pre-build script looks as follows:

package main

import (
    "github.com/pieterclaerhout/go-james"
    "github.com/pieterclaerhout/go-log"
)

func main() {

    args, err := james.ParseBuildArgs()
    log.CheckError(err)

    log.InfoDump(args, "pre_build arguments")

}

You can also execute a script after the build. To do so, create a file <project_root>/scripts/post_build/post_build.go with contents similar to:

package main

import (
    "github.com/pieterclaerhout/go-james"
    "github.com/pieterclaerhout/go-log"
)

func main() {

    args, err := james.ParseBuildArgs()
    log.CheckError(err)

    log.InfoDump(args, "post_build arguments")

}

Parsing arguments in pre/post build scripts.

To parse the arguments, you can use james.ParseBuildArgs().

The parameters it gets are are struct of the type james.BuildArgs:

james.BuildArgs{
  ProjectPath: "/home/user/go-james",
  OutputPath: "/home/user/go-james/build/go-james",
  GOOS: "darwin",
  GOARCH: "amd64",
  ProjectName: "go-james",
  ProjectDescription: "James is your butler and helps you to create, build, test and run your Go projects",
  ProjectCopyright: "© 2019-2020 Copyright Pieter Claerhout",
  Version: "0.7.0",
  Revision: "2065b13",
  Branch: "master",
  RawBuildCommand: []string{
    "go",
    "build",
    "-o",
    "build/go-james",
    "-ldflags",
    "-s -w -X github.com/pieterclaerhout/go-james/versioninfo.ProjectName=go-james -X 'github.com/pieterclaerhout/go-james/versioninfo.ProjectDescription=James is your butler and helps you to create, build, test and run your Go projects' -X 'github.com/pieterclaerhout/go-james/versioninfo.ProjectCopyright=© 2019 Copyright Pieter Claerhout' -X github.com/pieterclaerhout/go-james/versioninfo.Version=0.7.0 -X github.com/pieterclaerhout/go-james/versioninfo.Revision=2065b13 -X github.com/pieterclaerhout/go-james/versioninfo.Branch=master",
    "-trimpath",
    "github.com/pieterclaerhout/go-james/cmd/go-james",
  },
}

The same information is also available in the following environment variables:

GO_JAMES_BRANCH="master"
GO_JAMES_GOARCH="amd64"
GO_JAMES_GOOS="darwin"
GO_JAMES_OUTPUT_PATH="/home/user/go-james/build/go-james"
GO_JAMES_PROJECT_COPYRIGHT="© 2019-2020 Copyright Pieter Claerhout"
GO_JAMES_PROJECT_DESCRIPTION="James is your butler and helps you to create, build, test and run your Go projects"
GO_JAMES_PROJECT_NAME="go-james"
GO_JAMES_PROJECT_PATH="/home/user/go-james"
GO_JAMES_REVISION="2065b13"
GO_JAMES_VERSION="0.7.0"

Using Bash scripts for pre/post build actions.

If you prefer to use a bash script instead for the pre/post build actions, you can create a file called:

<project_root>/scripts/post_build/pre_build.sh

or

<project_root>/scripts/post_build/post_build.sh

It should be marked as executable.

Using Batch files for pre/post build actions.

If you prefer to use a batch file on Windows instead for the pre/post build actions, you can create a file called:

<project_root>/scripts/post_build/pre_build.bat

or

<project_root>/scripts/post_build/post_build.bat

How go-james defines which pre/post build script to run

go-james will search for pre/post build scripts in the following order:

  • pre_build.go / post_build.go
  • pre_build.sh / post_build.sh
  • pre_build.bat / post_build.bat

Packaging a project

From within the project root, run the package command to build the executable for windows / darwin / linux in the 386 and amd64 variants and compresses the result as a .zip (windows) or .tgz (linux / mac):

go-james package [-v] [--concurrency=4]

By default, the output is put in the build subdirectory but can be customized in the configuration file.

The filenames which are constructed use the following convention:

build/<project.name>_<goos>-<goarch>_v<project.version>.[zip,tgz]

The executable will be compressed and, if present in the project, the project's README.md file as well.

You can specify the following options:

  • -v: the packages which are built will be listed.
  • --concurrency: how many package processes should run in parallel, defaults to the number of CPUs.

As part of the build process, the versioninfo package will be filled with the following details:

  • versioninfo.ProjectName: the name of the project from the configuration file
  • versioninfo.ProjectDescription: the description of the project from the configuration file
  • versioninfo.Version: the version of the project from the configuration file
  • versioninfo.Revision: the current Git commit hash
  • versioninfo.Branch: the current Git branch name

With every build, these variables are automatically updated.

Debugging a project

From within the project root, run:

go-james debug

This will build the project and run it's main target through the Delve debugger. If the dlv command is not yet present in your $GOPATH/bin folder, it will automaticall be installed the first time you run it.

When creating a new project or performing init on an existing project, it also configures debugging from within Visual Studio Code. It's a simple as setting one or more breakpoints and choose "Start" > "Debug" from the menu. It creates a launch configuration called Debug.

Running a project

From within the project root, run:

go-james run <args>

This will build the project and run it's main target passing the <args> to the command.

Testing a project

From within the project root, run:

go-james test

This will run all the tests defined in the package.

Installing the executable

To install the main executable of your project in $GOPATH/bin, simply run the install command.

This will build the project and install it in the $GOPATH/bin folder. The name of the executable is the basename of build output path (as specified in the configuration file.

go-james uninstall

Uninstalling the executable

Similar to the install command, there is also an uninstall command which removes the executable from $GOPATH/bin.

go-james uninstall

Running a static analysis

You can use the staticcheck command to run the staticcheck static analyzer. The binary required to run staticcheck is automatically installed if needed.

go-james staticcheck

Building a Docker image

You can use the docker-image command to build a Docker image using the Dockerfile in the project folder. When you create a new project, a starter Dockerfile will be created automatically.

go-james docker-container

The config file go-james.json

When you create a new project or init an existing one, a go-james.json file will be created in the root of your project. This file can be used to configure the project. The full config file is as follows:

{
    "project": {
        "name": "go-example",
        "version": "1.0.0",
        "description": "",
        "copyright": "",
        "package": "github.com/pieterclaerhout/go-example",
        "main_package": "github.com/pieterclaerhout/go-example/cmd/go-example"
    },
    "build": {
        "output_path": "build/go-example",
        "ld_flags": [
            "-s",
            "-w"
        ],
        "ld_flags_windows": [
            "-s",
            "-w",
            "-H",
            "windowsgui"
        ],
        "ld_flags_darwin": [],
        "ld_flags_linux": [],
        "extra_args": [
            "-trimpath"
        ],
        "use_gotip": false
    },
    "run": {
        "environ": {
            "var": "val"
        }
    },
    "package": {
        "include_readme": true
    },
    "test": {
        "extra_args": []
    },
    "staticcheck": {
        "checks": ["all", "-ST1005", "-ST1000"]
    },
    "docker-image": {
        "name": "go-james",
        "repository": "pieterclaerhout/go-james",
        "tag": "revision",
        "prune_images_after_build": false
    }
}

Project Config

  • name: the name of your project (will be availabme under <package>/versioninfo.ProjectName)
  • version: the version of your project (will be availabme under <package>/versioninfo.Version)
  • description: the description of your project (will be availabme under <package>/versioninfo.ProjectDescription)
  • copyright: the description of your project (will be availabme under <package>/versioninfo.ProjectCopyright)
  • package: the root package of your project
  • main_package: the full path to the main package of your app, defaults to <package>/cmd/<project-name>

Build Config

  • output_path: the path where the built executable should be placed. Defaults to build/<project-name>
  • ld_flags: the linker flags you want to use for building. You can find more info about these flags here. These are only used if you don't specify specific parameters for a specifc GOOS.
  • ld_flags_darwin: the linker flags you want to use for building darwin. You can find more info about these flags here.
  • ld_flags_linux: the linker flags you want to use for building for linux. You can find more info about these flags here.
  • ld_flags_windows: the linker flags you want to use for building for windows. You can find more info about these flags here.
  • extra_args: contains any extra command-line parameters you want to add to the go build command when you run go-james build.
  • use_gotip: setting this to true uses gotip to compile instead of the regular gocommand. Make sure you have gotip installed.

Run Config

  • environ: the environment variables to use when running the app

Package Config

  • include_readme: boolean indicating if the README.md file should be included in the package or not

Test Config

  • extra_args: contains any extra command-line parameters you want to add to the go test command when you run go-james test.

Staticcheck Config

Docker Image Config

  • name: the name of the docker image you want to create. Defaults to the project name.
  • repository: the repository to which you want to push the image. If left empty, the image will only be created locally.
  • tag: can be either revision or version (the default) and indicates what value should be used for the tag.
  • prune_images_after_build: if set to true, a docker image prune -f will be executed after the docker build step.

Bootstrapping go-james

If you want to build go-james from scratch, you can use the following command (or use the "bootstrap" build task in Visual Studio Code):

go build -v -o build/go-james github.com/pieterclaerhout/go-james/cmd/go-james

If you have a version of go-james installed, you can use it to build itself.

Roadmap

To get an idea on what's coming, you can check the GitHub Milestones.

Resources

Follow my weblog about Go & Kubernetes :-)

Author: Pieterclaerhout
Source Code: https://github.com/pieterclaerhout/go-james 
License: Apache-2.0 license

#go #golang #testing #debugging 

Erstellen Sie Ihre eigene Kryptowährungs-Blockchain in Python

Kryptowährung ist eine dezentralisierte digitale Währung, die Verschlüsselungstechniken verwendet, um die Erzeugung von Währungseinheiten zu regulieren und den Geldtransfer zu überprüfen. Anonymität, Dezentralisierung und Sicherheit gehören zu seinen Hauptmerkmalen. Kryptowährung wird von keiner zentralisierten Behörde, Regierung oder Bank reguliert oder verfolgt.

Blockchain, ein dezentralisiertes Peer-to-Peer (P2P)-Netzwerk, das aus Datenblöcken besteht, ist ein wesentlicher Bestandteil der Kryptowährung. Diese Blöcke speichern chronologisch Informationen über Transaktionen und halten sich an ein Protokoll für die Kommunikation zwischen Knoten und die Validierung neuer Blöcke. Die in Blöcken aufgezeichneten Daten können nicht geändert werden, ohne dass alle nachfolgenden Blöcke geändert werden.

In diesem Artikel erklären wir, wie Sie mit der Programmiersprache Python eine einfache Blockchain erstellen können.

Hier ist die grundlegende Blaupause der Python-Klasse, die wir zum Erstellen der Blockchain verwenden:

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

Lassen Sie uns nun erklären, wie die Blockchain-Klasse funktioniert.

Ausgangsstruktur der Blockklasse

Hier ist der Code für unsere anfängliche Blockklasse:

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()

Wie Sie oben sehen können, nimmt der Klassenkonstruktor oder die Initiationsmethode ( init ()) die folgenden Parameter an:

self— Wie jede andere Python-Klasse wird dieser Parameter verwendet, um auf die Klasse selbst zu verweisen. Auf jede Variable, die der Klasse zugeordnet ist, kann über sie zugegriffen werden.

index — Es wird verwendet, um die Position eines Blocks innerhalb der Blockchain zu verfolgen.

previous_hash — Es wurde verwendet, um auf den Hash des vorherigen Blocks innerhalb der Blockchain zu verweisen.

data—it gibt Details zu den getätigten Transaktionen an, zum Beispiel den gekauften Betrag.

timestamp—it fügt einen Zeitstempel für alle durchgeführten Transaktionen ein.

Die zweite Methode in der Klasse, compute_hash , wird verwendet, um den kryptografischen Hash jedes Blocks basierend auf den obigen Werten zu erzeugen.

Wie Sie sehen können, haben wir den SHA-256-Algorithmus in das Kryptowährungs-Blockchain-Projekt importiert, um die Hashes der Blöcke zu erhalten.

Sobald die Werte im Hashing-Modul platziert wurden, gibt der Algorithmus einen 256-Bit-String zurück, der den Inhalt des Blocks angibt.

Das ist es, was der Blockchain Unveränderlichkeit verleiht. Da jeder Block durch einen Hash repräsentiert wird, der aus dem Hash des vorherigen Blocks berechnet wird, führt die Beschädigung eines Blocks in der Kette dazu, dass die anderen Blöcke ungültige Hashes haben, was zum Bruch des gesamten Blockchain-Netzwerks führt.

Aufbau der Kette

Das ganze Konzept einer Blockchain basiert darauf, dass die Blöcke aneinander „verkettet“ sind. Jetzt erstellen wir eine Blockchain-Klasse, die die entscheidende Rolle bei der Verwaltung der gesamten Kette spielt.

Es behält die Transaktionsdaten bei und enthält andere Hilfsmethoden zum Vervollständigen verschiedener Rollen, z. B. das Hinzufügen neuer Blöcke.

Sprechen wir über die Hilfsmethoden.

Hinzufügen der Konstruktormethode

Hier ist der Code:

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

Die Konstruktormethode init () instanziiert die Blockchain.

Hier sind die Rollen seiner Attribute:

self.chain — Diese Variable speichert alle Blöcke.

self.current_data — Diese Variable speichert Informationen über die Transaktionen im Block.

self.build_genesis() — Diese Methode wird verwendet, um den Anfangsblock in der Kette zu erstellen.

Aufbau des Genesis-Blocks

Die build_genesis()Methode wird verwendet, um den Anfangsblock in der Kette zu erstellen, dh einen Block ohne Vorgänger. Der Genesis-Block ist der Anfang der Blockchain.

Um es zu erstellen, rufen wir die build_block()Methode auf und geben ihr einige Standardwerte. Die Parameter proof_numberund previous_hasherhalten beide den Wert Null, Sie können ihnen jedoch jeden beliebigen Wert zuweisen.

Hier ist der 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

Bestätigung der Gültigkeit der Blockchain

Die confirm_validityMethode ist entscheidend, um die Integrität der Blockchain zu überprüfen und sicherzustellen, dass Inkonsistenzen fehlen.

Wie bereits erwähnt, sind Hashes von entscheidender Bedeutung für die Realisierung der Sicherheit der Kryptowährungs-Blockchain, da jede geringfügige Änderung an einem Objekt zur Erstellung eines völlig anderen Hashs führt.

Somit verwendet das confirm_validityVerfahren eine Reihe von if-Anweisungen, um zu beurteilen, ob der Hash jedes Blocks kompromittiert wurde.

Darüber hinaus vergleicht es auch die Hash-Werte von jeweils zwei aufeinanderfolgenden Blöcken, um Anomalien zu identifizieren. Wenn die Kette richtig funktioniert, gibt sie true zurück; Andernfalls wird false zurückgegeben.

Hier ist der 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

Deklarieren von Transaktionsdaten

Die get_dataMethode ist wichtig, um die Daten von Transaktionen in einem Block zu deklarieren. Diese Methode verwendet drei Parameter (Absenderinformationen, Empfängerinformationen und Betrag) und fügt die Transaktionsdaten zur Liste self.current_data hinzu.

Hier ist der Code:

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

Bewirken des Arbeitsnachweises

In der Blockchain-Technologie bezieht sich Proof of Work (PoW) auf die Komplexität, die mit dem Mining oder der Generierung neuer Blöcke auf der Blockchain verbunden ist.

Zum Beispiel kann das PoW implementiert werden, indem eine Zahl identifiziert wird, die ein Problem löst, wenn ein Benutzer eine Rechenarbeit abschließt. Jeder im Blockchain-Netzwerk sollte den Zahlenkomplex identifizieren, aber leicht zu überprüfen finden – dies ist das Hauptkonzept von PoW.

Auf diese Weise verhindert es Spam und gefährdet die Integrität des Netzwerks.

In diesem Artikel veranschaulichen wir, wie Sie einen Proof of Work-Algorithmus in ein Blockchain-Kryptowährungsprojekt einbinden.

Abschluss mit dem letzten Block

Schließlich wird die Hilfsmethode Latest_block() verwendet, um den letzten Block im Netzwerk abzurufen, der tatsächlich der aktuelle Block ist.

Hier ist der Code:

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

Implementieren von Blockchain-Mining

Das ist jetzt der spannendste Abschnitt!

Anfänglich werden die Transaktionen in einer Liste nicht verifizierter Transaktionen geführt. Mining bezieht sich auf den Prozess, die ungeprüften Transaktionen in einen Block zu legen und das PoW-Problem zu lösen. Es kann als die Rechenarbeit bezeichnet werden, die bei der Überprüfung der Transaktionen beteiligt ist.

Wenn alles richtig herausgefunden wurde, wird ein Block erstellt oder abgebaut und mit den anderen in der Blockchain zusammengefügt. Wenn Benutzer einen Block erfolgreich abgebaut haben, werden sie oft dafür belohnt, dass sie ihre Computerressourcen zur Lösung des PoW-Problems verwenden.

Hier ist die Mining-Methode in diesem einfachen Kryptowährungs-Blockchain-Projekt:

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)

Zusammenfassung

Hier ist der gesamte Code für unsere Krypto-Blockchain-Klasse 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)

Lassen Sie uns nun versuchen, unseren Code auszuführen, um zu sehen, ob wir einige digitale Münzen generieren können ...

Wow, es hat funktioniert!

Abschluss

Das ist es!

Wir hoffen, dass dieser Artikel Ihnen geholfen hat, die zugrunde liegende Technologie zu verstehen, die Kryptowährungen wie Bitcoin und Ethereum antreibt.

Wir haben gerade die Grundideen veranschaulicht, um Ihre Füße in der innovativen Blockchain-Technologie nass zu machen. Das obige Projekt kann noch verbessert werden, indem andere Funktionen integriert werden, um es nützlicher und robuster zu machen.