Solidity method taking in bytes32 and hashing but values with previous hash don't match - hash

Here's the code:
function playGame(bytes32 hashedMove) public returns (bool) {
require(
playerOne != address(0x0) && playerTwo != address(0x0),
"Game needs more players to join first"
);
require(
msg.sender == playerOne || msg.sender == playerTwo,
"You did not join the game as a player"
);
if (msg.sender == playerOne && hashedPlayerOneMove == "") {
hashedPlayerOneMove = hashedMove;
emit PlayerMadeMove(playerOne);
} else if (msg.sender == playerTwo && hashedPlayerTwoMove == "") {
hashedPlayerTwoMove = hashedMove;
emit PlayerMadeMove(playerTwo);
} else {
return false;
}
return true;
}
The above method takes in a hashedMove argument which I am using the following site to get: https://emn178.github.io/online-tools/keccak_256.html
I send a value of 2test2 hashed which is 0x0698472c4668bddd0c694601ca101551bd7b5cfe6dc780ab37bccfc99ad22e4c
Now another method takes in the constituents of the hash which are 2 and test2 to compare it with the stored hash:
function revealPlayerChoice(uint256 move, bytes32 password)
public
returns (uint256)
{
require(
hashedPlayerOneMove != bytes32(0x0) &&
hashedPlayerTwoMove != bytes32(0x0),
"The game is still running!"
);
bytes32 hashedAnswer = getSaltedHash(move, password);
console.logBytes32(hashedAnswer);
console.logBytes32(hashedPlayerOneMove);
if (msg.sender == playerOne && hashedAnswer == hashedPlayerOneMove) {
playerOneMove = move;
} else if (
msg.sender == playerTwo && hashedAnswer == hashedPlayerTwoMove
) {
playerTwoMove = move;
}
if (playerOneMove != 0 && playerTwoMove != 0) {
getGameOutcome();
}
}
I'm sending 2 as uint and 0x0000000000000000000000000000000000000000000000000000007465737432 (test2 in bytes) to the revealPlayerChoice method. However the values I'm getting from the console log are different. hashedAnswer is the hash I'm calculating in the method and hashedPlayerOneMove is the hash stored in playGame method.
for example, The console log outputs are
0x566d7dd4e9dc72e9beef887f2982703a0d0f9dd1b6505ee3ff5310c7383637bd
0x0698472c4668bddd0c694601ca101551bd7b5cfe6dc780ab37bccfc99ad22e4c
I would like to understand why the values are different? I'm using keccak256 to hash in solidity (pragma solidity ^0.8.0;) as well:
function getSaltedHash(uint answer, bytes32 salt) pure returns (bytes32) {
return keccak256(abi.encodePacked(answer, salt));
}

The key to your problem might be what abi.encodePacked(answer, salt) is returning.
When you pass the following arguments:
uint256 answer = 2
bytes32 salt = 0x0000000000000000000000000000000000000000000000000000007465737432
abi.encodePacked(answer, salt) returns:
0x00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000007465737432
And then, if you run the keccak256(bytes) with the previous value, it returns:
0x566d7dd4e9dc72e9beef887f2982703a0d0f9dd1b6505ee3ff5310c7383637bd

Related

how to handle adding null values with eachother

I want to input three numbers into TextFormFields. The controllers are numOneController and numTwoController for putting the percent and a totalAmountController for putting the the amount. I then want to check if the percents are in total 100 so i can display they are indeed so. When totalAmountController is empty(null) then its no problem to display that its an invalid input but when the numOneController and numTwoController are empty i get the error Invalid number (at character 1). I know its the fact that handler can't add an empty number with another. But how can i handle this so i can check if its null then i want to assign a number 0 to add that automaticly.
sumHandler() {
var totalPrecent = int.parse(numOneController.text) +
int.parse(numTwoController.text) ;
var totalAmount = totalAmountController;
if (totalPrecent == 100 && totalAmount.text.isEmpty == false) {
debugPrint(totalPrecent.toString());
debugPrint(totalAmount.text.toString());
} else {
debugPrint("invalid input");
}
}
Using the tryParse method and a default value would help...
sumHandler() {
var totalPrecent = int.tryParse(numOneController.text) ?? 0 +
int.tryParse(numTwoController.text) ?? 0;
var totalAmount = totalAmountController;
if (totalPrecent == 100 && totalAmount.text.isEmpty == false) {
debugPrint(totalPrecent.toString());
debugPrint(totalAmount.text.toString());
} else {
debugPrint("invalid input");
}
}
So i found the solution for this on: Another exception was thrown: FormatException: Invalid number (at character 1)
I had to use try catch block:
try {
firstNumber = int.parse(numOneController.text);
} on FormatException {
firstNumber = 0;
}
This way i can handle the exception and on FormatException i can assign the number 0.
Create a temp variable and store it with 0 and later if the textfield has values assign values to it. Like the following
sumHandler() {
int firstNumber = 0;
int secondNumber = 0;
if(numOneController.text != "")
{
firstNumber = int.parse(numOneController.text);
}
if(numTwoController.text != "")
{
secondNumber = int.parse(numTwoController.text);
}
var totalPresent = firstNumber + secondNumber ;
var totalAmount = totalAmountController;
if (totalPresent == 100 && totalAmount.text.isEmpty == false) {
debugPrint(totalPresent.toString());
debugPrint(totalAmount.text.toString());
} else {
debugPrint("invalid input");
}
}

Check name of list key and change it

I am trying to check the name of a key in a list and then change the name if it meets a certain criteria.
My code so far is:
String convert(double key) {
if(key == '1') {
return "One";
} else if(key == '2') {
return "Two";
}
//This the the list loop:
for (var entry in optoins.entries) {
entry.key = convert(entry.key); //This seems to be incorrect
if (entry.key == "One") {
//do somehting
}
}
The error I get is this one:
The argument type 'String' can't be assigned to the parameter type 'double'.
I know I can do if (entry.key == "1") but later in the code I need entry.key to be a string One and not 1, so I would like to change the name before starting the if else check.
The problem is your code entry.key is a double variable and not a string. I would suggest adding a new field to the entry class called stringKey and store this value there. That would be something like
String convert(String key) {
if(key == '1') {
return "One";
} else if(key == '2') {
return "Two";
}
//This the the list loop:
for (var entry in optoins.entries) {
entry.stringKey= convert(str(entry.key)); //This seems to be incorrect
if (entry.stringKey== "One") {
//do somehting
}
}

How do i sort a field if I am receiving null at some places in dart?

I am making a firebase query for which this is the output. How do i sort it to (1,2,null,null) order?
I have tried list.sort((a,b)=> a[fieldName].compareTo(b[fieldName])
Assuming you're looking for a solution in dart, you need to provide a sorting function that handles null values, which is something your current solution does not even attempt to do.
The following shows a sorting function that checks if either of the terms are null and handles it accordingly. Otherwise, it uses the default compareTo.
list.sort((a,b) {
if(a == null && b == null) {
return 0;
}
if(a == null) {
return 1;
}
if(b == null) {
return -1;
}
else {
return a.compareTo(b);
}
});

how can I write generic queries in entity framework?

I have 3 methods these are same methods only some parameters will be change I want to write one method how can i write
public string method1(int id)
{
var getAllStudents = rep.Students.Where(e => e.StudentId == id).ToList();
foreach (var item in getAllStudents)
{
if (item.isActive != true)
return "Error";
}
return "OK";
}
public string method2(int id)
{
var getAllTeachers = rep.Teachers.Where(e => e.TeacherId == id).ToList();
foreach (var item in getAllTeachers)
{
if (item.isActive != true)
return "Error";
}
return "OK";
}
public string method3(int id)
{
var getAllClasses = rep.Classes.Where(e => e.ClassId == id).ToList();
foreach (var item in getAllClasses)
{
if (item.isActive != true)
return "Error";
}
return "OK";
}
I think there is very easy way to write 1 method. the think is where parameter has different id..
Thanks.
Avoid conditional logic based on arguments. This leads to fragile code because every parameter combination has to be tested to be considered reliable. This leads to complex code that is easily prone to bugs. Having simpler single-purpose methods are typically much more reliable and easier to understand and maintain.
For instance given your example and assuming that "rep" was your instance's DbContext...
public bool IsActiveStudent(int id)
{
bool result = rep.Students.Any(x => x.StudentId == id && x.IsActive);
return result;
}
public bool IsActiveTeacher(int id)
{
bool result = rep.Teachers.Any(x => x.TeacherId == id && x.IsActive);
return result;
}
public bool IsActiveClass(int id)
{
bool result = rep.Classes.Any(x => x.ClassId == id && x.IsActive);
return result;
}
These can be essentially one-liners by simply returning the .Any() result. I tend to favour selecting the result into a variable first and returning it on a separate line since it makes it easier to breakpoint and inspect.
If you need to return a string for "Ok" vs. "Error" then:
return result ? "OK" : "Error";
Methods should strive to do one thing, and do it well. Easy to understand and troubleshoot if need be. Adding parameters and conditional code inside the method merely makes the code more volatile and leaves openings for bugs. In the end it doesn't make the code much shorter when the initial method could be simplified.
You can not overload methods if they signatures are the same.
You have two methods with the same signature:
public string checkexist(int id)
What you can do is to rename your methods, like this:
public interface WriteSomethingHere {
public boolean isStudentExist(int id);
public boolean isTeacherExist(int id);
public boolean isClassExist(int id);
}
I just found answer using generic repo
public T GetEntity<T>(int Id)
where T : class
{
using (MyEntities rpContext = new MyEntities())
{
return rpContext.Set<T>().Find(e => e.Id == Id);
}
}
after calling
var entityStudent = GetEntity<Student>(1);
var entityTeacher = GetEntity<Teacher>(1);
var entityClasses = GetEntity<Classes>(1);
You have Create Enumeration
Public Enum ParameterStaus:short
{
Student=1,
Teacher=2,
Classess=3
}
public string method2(int id.ParameterStatus status)
{
if(status==ParameterStatus.Teacher)
{
var getAllTeachers = rep.Teachers.Where(e => e.TeacherId == id).ToList();
foreach (var item in getAllTeachers )
{
if (item.isActive != true)
return "Error";
}
return "OK";
}
}
Else if(status==ParameterStatus.Student)
{
var getAllStudents = rep.Students.Where(e => e.StudentId == id).ToList();
foreach (var item in getAllStudents)
{
if (item.isActive != true)
return "Error";
}
return "OK";
}
Else
{
var getAllClasses = rep.Classes.Where(e => e.ClassId == id).ToList();
foreach (var item in getAllClasses)
{
if (item.isActive != true)
return "Error";
}
return "OK";
}
}

how to validate zend form where at one field in required between two fields

I have two elements, adult no and children no, at least one field is required. How to validate this in zend framework and generate error message.
You need to create Your own validator. In this case i think You could use Zend_Validate_Identical, copy its code and change isValid method to something like this:
public function isValid($value, $context = null)
{
$this->_setValue((string) $value);
if (($context !== null) && isset($context) && array_key_exists($this->getToken(), $context)) {
$token = $context[$this->getToken()];
} else {
$token = $this->getToken();
}
if ($token === null) {
$this->_error(self::MISSING_TOKEN);
return false;
}
$strict = $this->getStrict();
// change != to ==
if (($strict && ($value === $token)) || (!$strict && ($value == $token)) && (&token =='' || $value == '') {
$this->_error(self::**YOUR_ERROR _CODE**);
return false;
}
return true;
}
This code is not tested but it should work :)