Bitcoin/address validation: Difference between revisions

m
syntax highlighting fixup automation
(→‎{{header|Raku}}: use openssl)
m (syntax highlighting fixup automation)
Line 40:
 
=={{header|Ada}}==
<langsyntaxhighlight lang=ada>with Ada.Exceptions, Interfaces;
with Ada.Streams;
use Ada.Exceptions, Interfaces;
Line 168:
end;
end Bitcoin_Addr_Validate;
</syntaxhighlight>
</lang>
 
{{out}}
Line 179:
 
=={{header|C}}==
<langsyntaxhighlight lang=c>#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
Line 239:
 
return 0;
}</langsyntaxhighlight>
Compile with -lcrypto
{{out}}
Line 251:
=={{header|C sharp|C#}}==
This requires [https://www.nuget.org/packages/NUnit/ NUnit package] to compile.
<langsyntaxhighlight lang=csharp>
using System;
using System.Linq;
Line 321:
}
}
</syntaxhighlight>
</lang>
 
=={{header|D}}==
This requires the D module from the SHA-256 Task.
{{trans|Go}}
<langsyntaxhighlight lang=d>import std.stdio, std.algorithm, std.array, std.string, sha_256_2;
 
struct A25 {
Line 410:
writefln(`"%s": %s`, test, err.empty ? "OK." : err);
}
}</langsyntaxhighlight>
{{out}}
<pre>"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i": OK.
Line 421:
This requires [https://pub.dev/packages/crypto Crypto package] to compile.
{{trans|Java}}
<langsyntaxhighlight lang=dart>import 'package:crypto/crypto.dart';
 
class Bitcoin {
Line 519:
return true;
}
}</langsyntaxhighlight>
{{out}}
<pre>"1BNGaR29FmfAqidXmD9HLwsGv9p5WVvvhq" true
Line 527:
=={{header|Delphi}}==
This requires [http://www.cityinthesky.co.uk/opensource/DCPcrypt/ DCPcrypt library] to compile.
<langsyntaxhighlight lang=delphi>
uses
DCPsha256;
Line 592:
raise Exception.Create('Bad digest');
end;
</syntaxhighlight>
</lang>
 
=={{header|Erlang}}==
Using base58 module from http://github.com/titan098/erl-base58.git.
 
<langsyntaxhighlight lang=Erlang>
-module( bitcoin_address ).
 
Line 615:
{checksum, Checksum} = {checksum, Four_bytes},
ok.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 628:
 
=={{header|Factor}}==
<langsyntaxhighlight lang=factor>USING: byte-arrays checksums checksums.sha io.binary kernel math
math.parser sequences ;
IN: rosetta-code.bitcoin.validation
Line 644:
 
: btc-valid? ( str -- ? ) base58> [ btc-checksum ] [ 4 tail* ] bi = ;
</syntaxhighlight>
</lang>
 
{{out}}
Line 654:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang=freebasic>' version 05-04-2017
' compile with: fbc -s console
 
Line 859:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>Bitcoin address: 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i is valid
Line 869:
=={{header|Go}}==
{{trans|C}}
<langsyntaxhighlight lang=go>package main
 
import (
Line 977:
os.Stderr.WriteString(m + "\n")
os.Exit(1)
}</langsyntaxhighlight>
{{out}}
Command line usage examples showing program exit status.
Line 1,004:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang=haskell>import Control.Monad (when)
import Data.List (elemIndex)
import Data.Monoid ((<>))
Line 1,062:
validate "1ANa55215ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" -- too long
validate "i55j" -- too short
</syntaxhighlight>
</lang>
{{out}}
<pre style="font-size:80%">"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" -> Valid
Line 1,073:
 
=={{header|Java}}==
<langsyntaxhighlight lang=java>import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
Line 1,141:
throw new AssertionError(String.format("Expected %s for %s, but got %s.", expected, address, actual));
}
}</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
{{trans|Python}}
<langsyntaxhighlight lang=julia>using SHA
 
bytes(n::Integer, l::Int) = collect(UInt8, (n >> 8i) & 0xFF for i in l-1:-1:0)
Line 1,183:
for (addr, corr) in addresses
println("Address: $addr\nExpected: $corr\tChecked: ", checkbcaddress(addr))
end</langsyntaxhighlight>
 
{{out}}
Line 1,215:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang=scala>import java.security.MessageDigest
 
object Bitcoin {
Line 1,274:
for (address in addresses)
println("${address.padEnd(36)} -> ${if (Bitcoin.validateAddress(address)) "valid" else "invalid"}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,294:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight lang=Mathematica>chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; data =
IntegerDigits[
FromDigits[
Line 1,303:
Hash[FromCharacterCode[
IntegerDigits[Hash[FromCharacterCode[data[[;; -5]]], "SHA256"],
256, 32]], "SHA256"], 256, 32][[;; 4]]</langsyntaxhighlight>
{{in}}
<pre>1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i
Line 1,316:
===Using “libssl”===
 
<langsyntaxhighlight lang=nim>import algorithm
 
const SHA256Len = 32
Line 1,396:
 
main()
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,414:
===Using “nimcrypto”===
{{libheader|nimcrypto}}
<langsyntaxhighlight lang=Nim>import nimcrypto
import strformat
 
Line 1,492:
 
for vector in testVectors:
vector.checkValidity()</langsyntaxhighlight>
 
{{out}}
Line 1,510:
=={{header|Oberon-2}}==
{{works with|oo2c}}{{libheader|Crypto}}
<langsyntaxhighlight lang=oberon2>
MODULE BitcoinAddress;
IMPORT
Line 1,591:
Out.Bool(Valid("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I"));Out.Ln
END BitcoinAddress.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,602:
 
=={{header|Perl}}==
<langsyntaxhighlight lang=perl>my @b58 = qw{
1 2 3 4 5 6 7 8 9
A B C D E F G H J K L M N P Q R S T U V W X Y Z
Line 1,633:
(pack 'C*', @byte[21..24]) eq
substr sha256(sha256 pack 'C*', @byte[0..20]), 0, 4;
}</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\bitcoin_address_validation.exw
Line 1,720:
<span style="color: #0000FF;">?</span><span style="color: #008000;">"done"</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
(No output other than "done" since all tests pass)
 
=={{header|PHP}}==
<langsyntaxhighlight lang=php>
function validate($address){
$decoded = decodeBase58($address);
Line 1,782:
main();
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,793:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight lang=PicoLisp>(load "sha256.l")
 
(setq *Alphabet
Line 1,822:
(valid "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!")
(valid "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz")
(valid "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz") ) )</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang=PureBasic>
; using PureBasic 5.50 (x64)
EnableExplicit
Line 1,903:
EndIf
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,913:
 
=={{header|Python}}==
<langsyntaxhighlight lang=python>from hashlib import sha256
 
digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
Line 1,930:
 
print(check_bc('1AGNa15ZQXAZUgFiqJ3i7Z2DPU2J6hW62i'))
print(check_bc("17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j"))</langsyntaxhighlight>
 
{{out}}
Line 1,940:
:Yuuki-chan edit: Delete this help if it's not needed anymore
:For those looking at examples here to try and work out what is required, the <code>n.to_bytes()</code> call is equivalent to this code which converts a (long) integer into individual bytes of a byte array in a particular order:
:<langsyntaxhighlight lang=python>>>> n = 2491969579123783355964723219455906992268673266682165637887
>>> length = 25
>>> list( reversed(range(length)) )
[24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> assert n.to_bytes(length, 'big') == bytes( (n >> i*8) & 0xff for i in reversed(range(length)))
>>> </langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang=racket>
#lang racket/base
 
Line 1,993:
(validate-bitcoin-address "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9") ; => #t
(validate-bitcoin-address "1badbadbadbadbadbadbadbadbadbadbad") ; => #f
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang=raku perl6line>sub sha256(blob8 $b) returns blob8 {
given run <openssl dgst -sha256 -binary>, :in, :out, :bin {
.in.write: $b;
Line 2,020:
/;
say "Here is a bitcoin address: 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" ~~ $bitcoin-address;</langsyntaxhighlight>
{{out}}
<pre>「1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i」</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang=ruby>
# Validate Bitcoin address
#
Line 2,042:
(n.length...42).each{n.insert(0,'0')}
puts "I think the checksum should be #{g}\nI calculate that it is #{Digest::SHA256.hexdigest(Digest::SHA256.digest(convert(n)))[0,8]}"
</syntaxhighlight>
</lang>
{{out}}
With A = '1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i'
Line 2,058:
This requires the [https://crates.io/crates/rust-crypto rust-crypto] crate for sha256.
<langsyntaxhighlight lang=Rust>
extern crate crypto;
 
Line 2,113:
Ok(res)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,123:
 
=={{header|Scala}}==
<langsyntaxhighlight lang=Scala>import java.security.MessageDigest
import java.util.Arrays.copyOfRange
 
Line 2,189:
println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart}ms]")
 
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
Line 2,200:
No external library is needed.
 
<langsyntaxhighlight lang=seed7>$ include "seed7_05.s7i";
include "msgdigest.s7i";
include "encoding.s7i";
Line 2,249:
checkValidationFunction("i55j", FALSE); # wrong length
checkValidationFunction("16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM", TRUE); # okay
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,276:
=={{header|Tcl}}==
{{tcllib|sha256}}
<langsyntaxhighlight lang=tcl>package require sha256
 
# Generate a large and boring piece of code to do the decoding of
Line 2,309:
}
return "$address is ok"
}</langsyntaxhighlight>
Testing if it works
<langsyntaxhighlight lang=tcl>puts [bitcoin_addressValid 1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9]
puts [bitcoin_addressValid 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i]</langsyntaxhighlight>
{{out}}
<pre>
Line 2,321:
=={{header|UNIX Shell}}==
{{works with|bash}}
<langsyntaxhighlight lang=bash>base58=({1..9} {A..H} {J..N} {P..Z} {a..k} {m..z})
bitcoinregex="^[$(printf "%s" "${base58[@]}")]{34}$"
 
Line 2,348:
else return 2
fi
}</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 2,355:
{{libheader|wren-str}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang=ecmascript>import "/crypto" for Sha256
import "/str" for Str
import "/fmt" for Conv, Fmt
Line 2,416:
for (address in addresses) {
Fmt.print("$-36s -> $s", address, Bitcoin.validateAddress(address) ? "valid" : "invalid")
}</langsyntaxhighlight>
 
{{out}}
Line 2,437:
=={{header|zkl}}==
Uses shared library zklMsgHash.
<langsyntaxhighlight lang=zkl>var [const] MsgHash=Import("zklMsgHash"); // SHA-256, etc
const symbols="123456789" // 58 characters: no cap i,o; ell, zero
"ABCDEFGHJKLMNPQRSTUVWXYZ"
Line 2,461:
(2).reduce(MsgHash.SHA256.fp1(1,dec),dec); // dec is i/o buffer
dec[0,4]==chkSum;
}</langsyntaxhighlight>
<langsyntaxhighlight lang=zkl>T("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i","1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X", // checksum changed, original data.
"1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", // data changed, original checksum.
"1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", // invalid chars
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz", // too long
).apply(coinValide).println();</langsyntaxhighlight>
{{out}}
<pre>L(True,True,False,False,False,False)</pre>
10,327

edits