how to read data from other Waves Oracles? - wavesplatform

how to read data from other Waves Oracles?
getInteger(OracleAddress, key)
key is String
I don't know in what type OracleAddress i should convert to
I tried
let OracleAddress = Address("3NAcoeWdUTWn8csXJPG47v1Fjtjcfqxb5tu".toBytes())
but doesn't work

When you do toBytes() with string value you actually get bytes from UTF8 string, but in your case address is an array of bytes converted to base58, so you only need to decode it from base58:
let OracleAddress = Address(base58'3NAcoeWdUTWn8csXJPG47v1Fjtjcfqxb5tu')
getIntegerValue(OracleAddress, key)

Related

Parsing Data Out of Dictionary<String, Any> in Swift

I'm trying to extract data out of a Dictionary<String, Any> in Swift. The dictionary returns the following when I run NSLog("\(terminalDict)"):
Optional(["DFEE22": <323c3c>, "DFEE20": <3c>, "DFEE21": <0a>, "DFEE17": <07>, "DFEE1E": , "DF10": <656e6672 65737a68>, "9F1C": <38373635 34333231>, "DFEE16": <00>, "DFEE15": <01>, "5F36": <02>, "DF11": <00>, "DFEE1F": <80>, "DFEE18": <80>, "9F1A": <0840>, "9F35": <21>, "9F4E": <31303732 31205761 6c6b6572 2053742e 20437970 72657373 2c204341 202c5553 412e>, "DF27": <00>, "DFEE1B": <30303031 35313030>, "DF26": <01>, "9F15": <1234>, "9F40": <f000f0a0 01>, "9F16": <30303030 30303030 30303030 303030>, "9F33": <6028c8>, "9F1E": <5465726d 696e616c>])
I want to get all the keys and values out of the dictionary and into one string variable (newSettings). This is how I was attempting to do that:
for (key, value) in terminalDict! {
NSLog("key is now= \(key)")
NSLog("value is now= \(value)")
let asString = value as! String
print(asString)
NSLog("Adding \(key) \(asString)")
newSettings = "\(newSettings)\(key)\(asString)"
}
which returns:
key is now= DFEE22
value is now= {length = 3, bytes = 0x323c3c}
Could not cast value of type 'NSConcreteMutableData' (0x204aff148) to 'NSString' (0x204afde30).
How can I get the "323c3c" out of the dictionary as a simple string without the length and bytes portion? I can't find much documentation on type 'NSConcreteMutableData'. Do I have to use substring functions in order to get rid of the "length=x bytes=" part? I'm guessing there's a better way to do this than manually getting the substrings. Thanks.
As Vadian says, your dictionaries contain Data values.
It looks like it is ASCII encoded text, but it's a bit hard to be sure.
This bit:
31303732 31205761 6c6b6572 2053742e 20437970 72657373 2c204341 202c5553 412e
Represents the string "10721 Walker St. Cypress, CA ,USA." when you treat it as ASCII.
you could use code like this:
for (key, value) in terminalDict! {
NSLog("key is now= \(key)")
// Decode the data into a String assuming it's ASCII
let asString = String(data: value, encoding: .ascii)
NSLog("value is now= '\(asString)'")
print(asString)
NSLog("Adding \(key) \(asString)")
newSettings = "\(newSettings)\(key)\(asString)"
}

How to add digest from sha256 to string in flutter?

I'm passing password into sha256. I successfully create sha256 and can also print it. The problem begins when I'm trying to convert digest.bytes into a string and append it.
import 'package:crypto/crypto.dart';
var url = "http://example_api.php?";
url += '&hash=';
// hash the password
var bytes = utf8.encode(password);
var digest = sha256.convert(bytes);
print("Digest as hex string: $digest");
url += String.fromCharCodes(digest.bytes);
This is printed: Digest as hex string: 03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4
This is appended to url: ¬gBóá\vá¥âUðg6#ȳ´Eùx×ÈFô
What am I doing wrong? I also tried utf8.decode method but using it gives me an error.
When you print digest, the print method will call digest.toString(), which is implemented to return a string of the digest bytes using a hexadecimal representation. If you want the same thing you have several options:
Call digest.toString() explicitly (or implicitly)
final digestHex = digest.toString(); // explicitly
final digestHex = '$digest'; // implicitly
Map the byte array to its hexadecimal equivalent
final digestHex = digest.bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
Use the convert package (this is what the crypto package does)
import 'package:convert/convert.dart';
...
final digestHex = hex.encode(digest.bytes);
The reason you are getting an error using utf8.decode is that your digest isn't an encoded UTF-8 string but a list of bytes that for all intents and purposes are completely random. You are trying to directly convert the bytes into a string, and doing so is easier if you can assume that they already represent a valid string. With the byte output from a hashing algorithm, though, you cannot safely make such an assumption.
However, if for some reason you still want to use this option, use the second optional parameter for utf8.decode to force it to try and decode the bytes anyway:
final digestString = utf8.decode(bytes, allowMalformed: true);
For reference, a byte list of [1, 255, 47, 143, 6, 80, 33, 202] results in "�/�P!�" where "�" represents an invalid/control character. You do not want to use this option, especially where the string will become part of a URL (as it's virtually guaranteed that the resulting string will not be web-safe).
For the hexadecimal representation of a Digest object, please explicitly call Digest.toString() (though in formatted strings, i.e. "url${digest}", this is done for you implicitly).
I'm frankly not familiar with String.fromCharCode, but I think it's looking for UTF-16 and not UTF-8 bits. I wrote a terminal example to show this, and how the outputs differ.
import 'dart:core';
import 'dart:convert';
import 'package:crypto/crypto.dart';
void main() {
const String password = "mypassword";
// hash the password
var bytes = utf8.encode(password);
var digest = sha256.convert(bytes);
// different formats
var bytesDigest = digest.bytes;
var hexDigest = digest.toString();
String url = "http://example_api.php?hash=";
print(url + hexDigest);
print(url + String.fromCharCodes(bytesDigest));
}
Output:
> dart test.dart
http://example_api.php?hash=89e01536ac207279409d4de1e5253e01f4a1769e696db0d6062ca9b8f56767c8
http://example_api.php?hash=à6¬ ry#Ö,©¸õggÈ

Base64 string reduces after putting Map (data structure) into json.decode(map)

I am converting an Image to base64 and then I am putting it into the Map data structure, but when I convert Map into the JSON string, base64 string reduces and gets the reduced length response from the server. My question is why is Map reducing it?
"Message": "Invalid length for a Base-64 char array or string."
Converting Image file to Base64
var imageBytes = pfImage.readAsBytesSync();
String base64Image = base64Encode(imageBytes);
print("base64 is =$base64Image");
putting into the map
var petData = Map<String, dynamic>();
petData['user_id'] = 55;
petData['name'] = "sdf";
petData['breed'] = "dsf";
petData['StrImageBase64'] =base64Image != null ? base64Image : "";
converting to json string
print("map>>" + json.encode(map));
Some More Info
I have checked it locally as well by putting base64string into map and then print it, the result is in reduced string.
petData['StrImageBase64'] ="/9j/4AAQSkZJRgABAQAAAQABAAD/4RllRXhpZgAASUkqAAgAAAAHABoBBQABAAAAYgAAABsBBQABAAAAagAAACgBAwABAAAAAgAAADIBAgAUAAAAcgAAABMCAwABAAAAAQAAAGmHBAABAAAAhgAAACWIBAABAAAA6AAAACoBAABIAAAAAQAAAEgAAAABAAAAMjAxOToxMToxMCAwNTo1NTozMwAHAACQBwAEAAAAMDIxMAGRBwAEAAAAAQIDAAqSBQABAAAA4AAAAACgBwAEAAAAMDEwMAGgAwABAAAA//8AAAKgBAABAAAAAAUAAAOgBAABAAAAwAMAAAAAAAAkEwAA6AMAAAIABwAFAAMAAAAGAQAAHQACAAsAAAAeAQAAAAAAAAAAAAABAAAANwAAAAEAAAAfAAAAAQAAADIwMTk6MTE6MTAAAAIAAQIEAAEAAABIAQAAAgIEAAEAAAAVGAAAAAAAAP/Y/+AAEEpGSUYAAQEAAAEAAQAA/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoUDg8MEBcUGBgXFBYWGh0lHxobIxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8AAEQgA8AFAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX2";
print("json.encode =${json.encode(petData)}");
UPDATED
It is not possible, that the map can reduce the value, or Json.decode(map) returns the reduced base64 string, Actually its VS code editor issue for not showing full base64 value.

Can I convert .png data into an Int in Swift?

I convert an image into .png data from a UIImageView and print result on console with this code:
let img = img_view.image!.pngData()
print(img)
The result of this snippet is 232206 Bytes
Can I get only 232206 as integer output, without the "bytes" suffix?
That's the size (number of bytes) of the Data, which you can access by .count:
let sizeOfData = img.count // 232206
After all, Data represents a collection of bytes, so it conforms to Collection, which has the count property.
Use count property:
let imgData = imgView.image!.pngData()
let imgBytesCount = imgData!.count
print(imgBytesCount)

Unable to understand how withUnsafeBytes method works

I am trying to convert Data to UnsafePointer. I found an answer here where I can use withUnsafeBytes to get the bytes.
Then I did a small test my self to see I could just print out the bytes value of the string "abc"
let testData: Data = "abc".data(using: String.Encoding.utf8)!
testData.withUnsafeBytes(
{(bytes: UnsafePointer<UInt8>) -> Void in
NSLog("\(bytes.pointee)")
})
But the output is just the value of one character, which is "a".
2018-07-11 14:40:32.910268+0800 SwiftTest[44249:651107] 97
How could I get the byte value of all three characters then?
The "pointer" points to the address of the first byte in the sequence. If you want to want a pointer to the other bytes, you have to use pointer arithmetic, that is, move the pointer to the next address:
testData.withUnsafeBytes{ (bytes: UnsafePointer<UInt8>) -> Void in
NSLog("\(bytes.pointee)")
NSLog("\(bytes.successor().pointee)")
NSLog("\(bytes.advanced(by: 2).pointee)")
}
or
testData.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Void in
NSLog("\(bytes[0])")
NSLog("\(bytes[1])")
NSLog("\(bytes[2])")
}
However, you must be aware of the byte size of testData and don't overflow it.
You are getting '97' because 'bytes' is pointing to the staring address of the 'testdata'.
you can get byte value of all three OR n number of characters like in the following code :
let testData: Data = "abc".data(using: String.Encoding.utf8)!
print(testData.count)
testData.withUnsafeBytes(
{(bytes: UnsafePointer<UInt8>) -> Void in
for idx in 0..<testData.count {
NSLog("\(bytes[idx])")
}
})